我有一個這樣的數組:失敗對工會陣列在PHP
Array
(
[6] => Array
(
[cate_id] => 6
[cate_name] => mobile
[cate_parent] => 0
[cate_order] => 2
[children] => Array
(
[17] => Array
(
[cate_id] => 17
[cate_name] => old styled phone
[cate_parent] => 6
[cate_order] => 2
[children] => Array
(
[24] => Array
(
[cate_id] => 24
[cate_name] => nokia1
[cate_parent] => 17
[cate_order] => 1
)
)
)
[18] => Array
(
[cate_id] => 18
[cate_name] => smart phone
[cate_parent] => 6
[cate_order] => 1
[children] => Array
(
[21] => Array
(
[cate_id] => 21
[cate_name] => apple
[cate_parent] => 18
[cate_order] => 1
)
[23] => Array
(
[cate_id] => 23
[cate_name] => nokia
[cate_parent] => 18
[cate_order] => 1
)
)
)
[20] => Array
(
[cate_id] => 20
[cate_name] => tablet
[cate_parent] => 6
[cate_order] => 3
)
)
)
[19] => Array
(
[cate_id] => 19
[cate_name] => accessories
[cate_parent] => 0
[cate_order] => 3
[children] => Array
(
[22] => Array
(
[cate_id] => 22
[cate_name] => phone case
[cate_parent] => 19
[cate_order] => 1
)
)
)
)
我寫這會得到特定類別的兒童IDS的功能。例如,如果我給「6」,它將返回17,24,18,21,23,20。這裏是我的功能:
function get_category_children($categories_tree, $parent)
{
//$children_list = '';
$children_list = array();
foreach ($categories_tree as $categories_branch)
{
if ($categories_branch['cate_parent'] == $parent)
{
$children_list[] = $categories_branch['cate_id'];
}
else
{
//echo "{$categories_branch['cate_id']},";
}
if(! empty($categories_branch['children']))
{
//echo "{$categories_branch['cate_id']},";
$children_list += get_category_children($categories_branch['children'], $categories_branch['cate_id']);
}
}
return $children_list;
}
但它只返回17,18,20。起初我還以爲有什麼問題在我的功能的邏輯,但是當我改變$ children_list的類型從數組字符串,像這樣:
function get_category_children($categories_tree, $parent)
{
$children_list = '';
//$children_list = array();
foreach ($categories_tree as $categories_branch)
{
if ($categories_branch['cate_parent'] == $parent)
{
$children_list .= $categories_branch['cate_id'].',';
}
else
{
//echo "{$categories_branch['cate_id']},";
}
if(! empty($categories_branch['children']))
{
//echo "{$categories_branch['cate_id']},";
$children_list .= get_category_children($categories_branch['children'], $categories_branch['cate_id']);
}
}
return $children_list;
}
它的工作原理神仙好,並返回我需要的一切,所以我覺得可能是$children_list += get_category_children($categories_branch['children'], $categories_branch['cate_id']);
有什麼問題,所以新陣列沒有添加到舊陣列,但我不知道爲什麼,以及如何解決它?
你能寫第二個例子的var_dump($ children_list;)嗎? –