数组排序每个孩子家长来后, [英] Sorting array for every child coming after parent
本文介绍了数组排序每个孩子家长来后,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的一个数组:
<?php
array(
array(
'id' => 1,
'parent_id' => null
),
array(
'id' => 2,
'parent_id' => 1
),
array(
'id' => 3,
'parent_id' => null
),
array(
'id' => 4,
'parent_id' => 2
)
)
我要每个孩子来到它的直接父后排序。因此,ID 4项应ID后2来的权利。
I need to sort it to every child comes after it's immediate parent. So, ID 4 item should come right after ID 2.
感谢。
推荐答案
工作液:PHP有用户定义排序功能的 uasort 我已经使用这个排序阵列。
Working solution : PHP has user define sorting function uasort I have used this to sort your array.
<?php
$data = array(
array(
'id' => 1,
'parent_id' => null
),
array(
'id' => 2,
'parent_id' => 1
),
array(
'id' => 3,
'parent_id' => null
),
array(
'id' => 4,
'parent_id' => 2
)
);
function cmp($a, $b) {
if ($a['parent_id'] == $b['parent_id']) {
return 0;
}
return ($a['parent_id'] < $b['parent_id']) ? -1 : 1;
}
uasort($data, 'cmp');
echo '<pre>';
print_r($data);
echo '</pre>';
这篇关于数组排序每个孩子家长来后,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文