Php 通过这样的多维数组进行Foreach循环
我在变量Php 通过这样的多维数组进行Foreach循环,php,arrays,multidimensional-array,foreach,Php,Arrays,Multidimensional Array,Foreach,我在变量$comments中有一个多维数组,包含: Array ( [0] => Array ( [0] => 889 [1] => First comment [2] => 8128912812 [3] => appr ) [1] => Array ( [0] => 2
$comments
中有一个多维数组,包含:
Array (
[0] => Array
(
[0] => 889
[1] => First comment
[2] => 8128912812
[3] => appr
)
[1] => Array
(
[0] => 201
[1] => This is the second comment
[2] => 333333
[3] => appr
)
// There is more...
)
如何循环此数组并使用for each回送每个值?您应该使用两个
foreach
循环,因为您的数组具有以下级别:
foreach($arrayOfArrays as $array){
foreach($array as $index => $value){
echo $array[$index];
}
}
foreach ($comments as $comment)
foreach ($comment as $comment_data)
echo $comment_data;
如果您的数组结构与显示的一样,则可以执行以下操作:
foreach($comments as $comment) {
echo $comment[0];
echo $comment[1];
echo $comment[2];
echo $comment[3];
}
只需使用两个foreach循环。一个在另一个里面
foreach($comments as $commentArray){
foreach($commentArray as $comment){
echo $comment;
}
}
希望这对您有所帮助$i=0;
$i=0;
$c=count($array);
while ($i<$c) {
foreach ($array[$i] as $comment_property) {
echo $comment_property;
}
$i++;
}
$c=计数($array);
虽然($I如何回显每个数组的每个值?@Henrik Petterson:你是什么意思?这个代码应该回显每个值。请看Mayous的答案,我是说像那样单独回显值。我如何在你的方法中做到这一点?@Henrik Petterson:我的方法做的事情完全相同,但代码更少,这也是一个通用的解决方案在上,以防内部数组具有不同数量的元素。我如何回显每个数组的每个值?您的意思是什么?上面的代码将回显每个数组中的每个值。请参阅Mayous的答案,我的意思是像那样单独回显值。在您的方法中,我如何做到这一点?请参阅我的编辑,您可以将$index
添加到foreach.我不知道你为什么需要这样做,如果你只需要回显$value
本身,但这就是你要寻找的吗?@Henrikpeterson这些回答中有没有回答你的问题?如果是这样,你应该接受其中一个作为正确答案。你能改变数组以获得合适的键吗?(id,text,user_id,意思是_index_3的_)@KA_lin No,太迟了:)