各ループで手動でforeachを記述せずに、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=5 L
配列要素2=6 M
配列要素1=2色
配列要素0=7白
配列要素1=8黒
配列要素2=3タイプ
配列要素0=9ポリエステル
配列要素1=10ライクラ
これが私のやり方だと思います…。
foreach($array as $item) {
foreach($item['children'] as $child) {
echo $child['stuff'];
}
}