递归函数输出一个野生的多维数组,希望它深一层 [英] Recursive function outputting a wild multidimentional array, would like it one level deep
本文介绍了递归函数输出一个野生的多维数组,希望它深一层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个递归函数,以追溯到深度未知的嵌套的根类别。
I am trying to write a recursive function that drills back to the root category of a nest of unknown depth.
[TABLE]
cat_id | cat_name | cat_parent | cat_slug
//each category with a cat_parent of 0 is a root category
[/TABLE]
示例SQL结果:
Array
(
[0] => Array
(
[cat_id] => 17
[cat_name] => another-test-category
[cat_parent] => 16
[cat_slug] => Another test category
)
)
功能:
function breadcrumb($cat_id){
$cat_nest =
SELECT *
FROM table
WHERE cat_id = '$cat_id'
//returns 1 row;
$cat_array[$cat_id] = $cat_nest[0];
if($cat_nest[0]['cat_parent'] != 0){
$cat_array[] = breadcrumb($cat_nest[0]['cat_parent']);
}
return $cat_array;
}
正在输出:
Array
(
[17] => Array
(
[cat_id] => 17
[cat_name] => test.example.1
[cat_parent] => 16
[cat_slug] => Test Example 1
)
[18] => Array
(
[16] => Array
(
[cat_id] => 16
[cat_name] => test.example.2
[cat_parent] => 15
[cat_slug] => Test Example 2
)
[17] => Array
(
[15] => Array
(
[cat_id] => 15
[cat_name] => test.example.3
[cat_parent] => 6
[cat_slug] => Test Example 3
)
[16] => Array
(
[6] => Array
(
[cat_id] => 6
[cat_name] => test.example.4
[cat_parent] => 2
[cat_slug] => Test Example 4
)
[7] => Array
(
[2] => Array
(
[cat_id] => 2
[cat_name] => test.example.5
[cat_parent] => 0
[cat_slug] => Test Example 5
)
)
)
)
)
)
所需的输出:
Array
(
[17] => Array
(
[cat_id] => 17
[cat_name] => test.example.1
[cat_parent] => 16
[cat_slug] => Test Example 1
)
[16] => Array
(
[cat_id] => 16
[cat_name] => test.example.2
[cat_parent] => 15
[cat_slug] => Test Example 2
)
[15] => Array
(
[cat_id] => 15
[cat_name] => test.example.3
[cat_parent] => 6
[cat_slug] => Test Example 3
)
[6] => Array
(
[cat_id] => 6
[cat_name] => test.example.4
[cat_parent] => 2
[cat_slug] => Test Example 4
)
[2] => Array
(
[cat_id] => 2
[cat_name] => test.example.5
[cat_parent] => 0
[cat_slug] => Test Example 5
)
)
推荐答案
我进行了一些测试,并且我认为该解决方案可以通过以下方式实现:
I ran some tests and I think the solution can be implemented this way:
function breadcrumb($cat_id){
$cat_nest =
SELECT *
FROM table
WHERE cat_id = '$cat_id'
//returns 1 row;
$cat_array[$cat_id] = $cat_nest[0];
if($cat_nest[0]['cat_parent'] != 0){
$cat_array = array_merge( $cat_array, breadcrumb($cat_nest[0]['cat_parent']) );
}
return $cat_array;
}
这将完全根据您的需要维护ID,因为这只会合并数组,而不会使用 $ cat_array []
This would maintain the IDs exactly as you need them, since this would only be merging arrays and not creating new indexes with $cat_array[]
这篇关于递归函数输出一个野生的多维数组,希望它深一层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文