PHP 数组仅打印每个项目的第一个字母

发布于 2024-11-08 07:30:44 字数 381 浏览 0 评论 0原文

下面的代码仅打印每个数组项的第一个字母。这让我很困惑。

require_once 'includes/global.inc.php';
print_r($site->bookmarkTags(1));

$index = 0;
foreach ($site->bookmarkTags(1) as $tag) {
    echo $tag['$index'];
    $index = $index + 1;
}

print_r 返回:

Array ( [0] => Wallpapers [1] => Free )

循环:

WF

The code below is only printing the first letter of each array item. It's got me quite baffled.

require_once 'includes/global.inc.php';
print_r($site->bookmarkTags(1));

$index = 0;
foreach ($site->bookmarkTags(1) as $tag) {
    echo $tag['$index'];
    $index = $index + 1;
}

print_r return:

Array ( [0] => Wallpapers [1] => Free )

the loop:

WF

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

冬天的雪花 2024-11-15 07:30:44

尝试 echo $tag,而不是 $tag['$index']

由于您使用的是 foreach,该值已经从数组中获取,当您发布 $tag['$index'] 时,它将打印 '$ 中的字符索引的位置:)

Try echo $tag, not $tag['$index']

Since you are using foreach, the value is already taken from the array, and when you post $tag['$index'] it will print the character from the '$index' position :)

聚集的泪 2024-11-15 07:30:44

看来您已经尝试做 foreach 已经在做的事情...
问题是您实际上是在回显非数组的 $index 字母,因为 foreach 已经在执行您似乎期望 $index = $index+1 执行的操作:

require_once 'includes/global.inc.php';
print_r($site->bookmarkTags(1));

$index = 0;
foreach ($site->bookmarkTags(1) as $tag) {
    echo $tag; // REMOVE [$index] from $tag, because $tag isn't an array
    $index = $index + 1; // You can remove this line, because it serves no purpose
}

It seems you've attempted to do what foreach is already doing...
The problem is that you're actually echoing the $index letter of a non-array because foreach is already doing what you seem to be expecting your $index = $index+1 to do:

require_once 'includes/global.inc.php';
print_r($site->bookmarkTags(1));

$index = 0;
foreach ($site->bookmarkTags(1) as $tag) {
    echo $tag; // REMOVE [$index] from $tag, because $tag isn't an array
    $index = $index + 1; // You can remove this line, because it serves no purpose
}
煞人兵器 2024-11-15 07:30:44
require_once 'includes/global.inc.php';

// Store the value temporarily instead of
// making a function call each time
$tags = $site->bookmarkTags(1);
foreach ($tags as $tag) {
    echo $tag;
}

这应该有效。问题可能是因为您每次迭代都进行函数调用,而不是临时存储值并对其进行循环。

require_once 'includes/global.inc.php';

// Store the value temporarily instead of
// making a function call each time
$tags = $site->bookmarkTags(1);
foreach ($tags as $tag) {
    echo $tag;
}

This should work. The issue might be because you're making a function call every iteration, versus storing the value temporarily and looping over it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文