[英]How to loop through N level Sub Child Array - PHP
我有類別和子類別。 我有這種類型的數組。
誰能幫助我如何遍歷n級。
Array
(
[0] => Array
(
[question_title] => hello.
[id] => 1
[step] => 1
[Children] => Array
(
)
)
[1] => Array
(
[question_title] => bye
[id] => 2
[step] => 1
[Children] => Array
(
)
)
[2] => Array
(
[question_title] => gtg
[id] => 3
[step] => 1
[Children] => Array
(
)
)
[3] => Array
(
[question_title] => cya
[id] => 4
[step] => 1
[Children] => Array
(
)
)
[4] => Array
(
[question_title] => not sure
[id] => 5
[step] => 1
[Children] => Array
(
)
)
[5] => Array
(
[question_title] => will see
[id] => 6
[step] => 1
[Children] => Array
(
)
)
[6] => Array
(
[question_title] =>idk
[id] => 7
[step] => 2
[Children] => Array
(
)
)
[7] => Array
(
[question_title] => mayebthis
[id] => 8
[step] => 2
[Children] => Array
(
)
)
[8] => Array
(
[question_title] => maybe this one as well
[id] => 9
[step] => 2
[Children] => Array
(
[0] => Array
(
[question_title] => maybe this one too
[id] => 10
[step] => 2
[Children] => Array
(
)
)
)
)
[9] => Array
(
[question_title] => and this
[id] => 11
[step] => 2
[Children] => Array
(
[0] => Array
(
[question_title] => or this
[id] => 12
[step] => 2
[Children] => Array
(
)
)
[1] => Array
(
[question_title] =>or here too
[id] => 13
[step] => 2
[Children] => Array
(
[0] => Array
(
[question_title] => wait i am also here
[id] => 14
[step] => 2
[Children] => Array
(
)
)
[1] => Array
(
[question_title] => me as well
[id] => 15
[step] => 2
[Children] => Array
(
)
)
[2] => Array
(
[question_title] => me me scream
[id] => 16
[step] => 2
[Children] => Array
(
)
)
)
)
)
)
[10] => Array
(
[question_title] => outside here
[id] => 17
[step] => 2
[Children] => Array
(
)
)
[11] => Array
(
[question_title] => outisde here too
[id] => 18
[step] => 2
[Children] => Array
(
)
)
)
我正在遍歷主數組,但是我不知道如何遍歷子數組,因為可能還有許多子子數組。
{foreach $question_master_array as $key => $val}
{if $question_master_array[$key]['step'] == 2}
<li><input type="checkbox" name="step1_question_{$question_master_array[$key]['question_id']}">{$question_master_array[$key]['question_title']}</li>
{if $question_master_array[$key]['Children']|@count gt 0}
... some stuff here ...
{/if}
{/if}
{/foreach}
因為我不能僅通過將鍵應用於Children數組來使其靜態,因為它可以具有n級。 好吧,這是我的tpl文件,因此我無法編輯以這種數據格式帶來的查詢。
您需要遞歸遍歷數組。
例如:
function recurSearch($array, $depth = 0)
{
echo ('Current depth : ' . $depth);
foreach ($array as $item)
{
echo ('id : ' . $item['id']);
echo ('question title : ' . $item['question_title']);
echo ('step : ' . $item['step']);
if (count($item['Children']) > 0)
{
echo 'child : ';
echo '{';
/*
* If $item['Children'] isn't empty,
* the function will be called again
* using $item['Children'] as main array
* That function will keep being called until $item['Children'] is empty
*/
recurSearch($item['Children'], $depth + 1);
echo '}';
}
else
{
echo ('child : no child');
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.