数组排序,将儿童的父母下方 [英] Sort an array, placing children beneath parents
本文介绍了数组排序,将儿童的父母下方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我在PHP项目的数组,有的可通过PARENT_ID键链接到别人。我期待,使任何物品,其父母为这个数组中结束父的正下方从右到这个数组排序。
So I have an array of items in php, some may be linked to others via a parent_id key. I'm looking to sort this array so that any items whose parent is in this array ends up positioned right below the parent.
例如:(实际数组有更多的键)
some_array[0]['id'] = 15001;
some_array[0]['parent_id'] = 14899;
some_array[1]['id'] = 14723;
some_array[1]['parent_id'] = 0; //parent_id of 0 means item has no parent of its own
some_array[2]['id'] = 14899;
some_array[2]['parent_id'] = 0;
some_array[3]['id'] = 15000;
some_array[3][parent_id'] = 14723;
我想,使他们在这个顺序结束整理这些:
some_array[0]['id'] = 14723;
some_array[1]['id'] = 15000;
some_array[2]['id'] = 14899;
some_array[3]['id'] = 15001;
IE浏览器。项目仅仅是他们的父母之下。
ie. items are just below their parents.
在此先感谢!
推荐答案
我的短版mattwang的回答:
My shorter version of mattwang's answer:
/**
* sort parents before children
*
* @param array $objects input objects with attributes 'id' and 'parent'
* @param array $result (optional, reference) internal
* @param integer $parent (optional) internal
* @param integer $depth (optional) internal
* @return array output
*/
function parent_sort(array $objects, array &$result=array(), $parent=0, $depth=0) {
foreach ($objects as $key => $object) {
if ($object->parent == $parent) {
$object->depth = $depth;
array_push($result, $object);
unset($objects[$key]);
parent_sort($objects, $result, $object->id, $depth + 1);
}
}
return $result;
}
只有实际的区别在于它排序对象数组,而不是数组的数组。
Only actual difference is that it sorts an array of objects instead of an array of arrays.
这篇关于数组排序,将儿童的父母下方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文