如何在不手动定义数组ID的情况下显示foreach输出?

时间:2013-01-10 21:23:35

标签: php arrays

Example of my arrays & output

如何管理我的foreach而不在每个循环上手动编写它?因为我不知道儿童用户的深度会选择。

$array['0']['children']
$array['1']['children']
$array['2']['children']

2 个答案:

答案 0 :(得分:2)

你应该创建一个递归函数来调用你的数组。

示例:

<html><body>
<h1>test</h1>
<?php

$array = array(
    '0' => array(
        'id' => 1, 
        'name' => 'Sizes',
        'parent' => 0,
        'children' => array(
            '0' => array('id' => 4, 'name' => 'S', 'parent' => 1),
            '1' => array('id' => 5, 'name' => 'L', 'parent' => 1),
            '2' => array('id' => 6, 'name' => 'M', 'parent' => 1)
        )
    ),
    '1' => array(
        'id' => 2,
        'name' => 'Colors',
        'parent' => 0,
        'children' => array(
            '0' => array('id' => 7, 'name' => 'White', 'parent' => 2),
            '1' => array('id' => 8, 'name' => 'Black', 'parent' => 2)
        )
    ),
     '2' => array(
        'id' => 3,
        'name' => 'Types',
        'parent' => 0,
        'children' => array(
            '0' => array('id' => 9, 'name' => 'Polyester', 'parent' => 3),
            '1' => array('id' => 10, 'name' => 'Lycra', 'parent' => 3)
        )
    )
 );


function my_recurse($array, $depth=0) {
   //to avoid infinite depths check for a high value
   if($depth>100) {  return; }  

   //


   foreach ($array as $id => $child) {
        echo "Array element $id = " . $child['id'] . " " . $child['name'] . "<br>\n";    //whatever you wanna output
     // test if got ghildren
     if(isset($child['children'])) {   
         my_recurse($child['children'], $depth+1); // Call to self on infinite depth. 
     }
   }
}



my_recurse($array);

?>
</body></html>

请注意!始终在函数中使用深度检查以避免无限递归。

这在我的浏览器中提供以下输出:

测试

数组元素0 = 1个大小

数组元素0 = 4 S

数组元素1 = 5 L

数组元素2 = 6 M

数组元素1 = 2种颜色

数组元素0 = 7白色

数组元素1 = 8黑色

数组元素2 = 3种类型

数组元素0 = 9涤纶

数组元素1 = 10莱卡

答案 1 :(得分:0)

我想我会这样做....

foreach($array as $item) {
    foreach($item['children'] as $child) {
          echo $child['stuff'];
    }
}
相关问题