PHP array only prints first letter of each item

烂漫一生 提交于 2019-12-13 05:40:00

问题


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

回答1:


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 :)




回答2:


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
}



回答3:


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.



来源:https://stackoverflow.com/questions/6050288/php-array-only-prints-first-letter-of-each-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!