问题描述
我试图创建,其中包含对类别ID和父ID的一个简单数组多维数组层次。类别可以是父,并在同一时间子类别。基础类具有为0的父(=无父)。例如:
i am trying to create a multidimensional array hierarchy from a simple array which contains pairs of category ids and parent ids. The categories can be a parent and a subcategory at the same time. The base categories have a parent of 0 (=no parent). For example:
# cat_id => parent_id
$initialArray = array(
1 => 0,
2 => 1,
3 => 2,
4 => 0,
5 => 4,
6 => 0
);
在此,我希望得到重新presents这样的结构数组:
From this, i'd like to get an array that represents a structure like this:
- 1
- 2
- 3
- 5
我不知道的内容
$ initialArray
事先我想看看其他类似的问题,但我无法找到答案。请帮助!
I tried to look at other similar questions but i couldn't find an answer. Please help!
推荐答案
那么在我看来,你需要一个递归函数。假设一切有父母或值在0的基础水平开始,我resituated阵列拥有所有父IDS列出自己的孩子,而不是上面的其他方式。在那之后,我创建了一个递归函数。
Well it appears to me you need a recursive function. Assuming everything has a parent or value beginning at the base level of 0, I resituated the array to have all parent ids listing their children rather than the other way around above. After that, I created a recursive function.
$initialArray = array( 1 => 0, 2 => 1, 3 => 2, 4 => 0, 5 => 4, 6 => 0 ); // resituate the array $parent_ids = array(); foreach ($initialArray as $category_id => $parent_id) { if (!isSet($parent_ids[$parent_id])) { $parent_ids[$parent_id] = array(); } $parent_ids[$parent_id][] = $category_id; } // end_array is the result $end_array = array(); /** * Takes the key of the parent, the current set that it's working off of, the list of parent ids for reference * and the current place in the end result array, acting recursively */ function recursive($parent_key, $current_set, $parent_ids, $end_array) { foreach ($current_set as $parent_value) { if (!isSet($parent_ids[$parent_value])) { $end_array[$parent_key][] = $parent_value; } else { // if the parent_value is found in parent_ids, pass those values to the same function and the current end_array position $end_array[$parent_key] = recursive($parent_value, $parent_ids[$parent_value], $parent_ids, $end_array[$parent_key]); } } return $end_array; } // start with the top most element $end_array = recursive(key($parent_ids), current($parent_ids), $parent_ids, $end_array); print '<pre>'. print_r($parent_ids, true). print_r($end_array,true). '</pre>' ;
输出:
// resituated array Array ( [0] => Array ( [0] => 1 [1] => 4 [2] => 6 ) [1] => Array ( [0] => 2 ) [2] => Array ( [0] => 3 ) [4] => Array ( [0] => 5 ) ) // the end result Array ( [0] => Array ( [1] => Array ( [2] => Array ( [0] => 3 ) ) [4] => Array ( [0] => 5 ) [5] => 6 ) )
这篇关于从阵列类别层次结构(CAT ID =&GT;父ID)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
- 2