数组示例&输出
我如何管理我的foreach而不需要在每个循环中手动编写它?因为我不知道深度的孩子用户会选择。
$array['0']['children']
$array['1']['children']
$array['2']['children']
你应该创建一个递归函数来调用你的数组。
的例子:
<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 = 5l
数组元素2 = 6m
数组元素1 = 2
数组元素0 = 7
数组元素1 = 8
数组元素2 = 3
数组元素0 = 9聚酯
元素1 = 10
我想这就是我要做的....
foreach($array as $item) {
foreach($item['children'] as $child) {
echo $child['stuff'];
}
}