Trying to mimic hierarchy by sorting array in PHP
I am trying to sort an array the following way in PHP:
array
0 => id:1203
parent_id: 456
1 => id:456
parent_id:1723
2 => id:1723
parent_id:0
to this:
ar开发者_StackOverflow社区ray
0 => id:1723
parent_id:0
1 => id:456
parent_id:1723
2 => id:1203
parent_id:456
I never sorted an array in PHP before. How would you do it?
Thanks
Is this doing what you want ?
$arr = array(
array('id' => 1203, 'parent_id' => 456),
array('id' => 456, 'parent_id' => 1723),
array('id' => 1723, 'parent_id' => 0)
);
function compare($a, $b) {
if ($a['parent_id'] == 0) return -1;
if ($b['parent_id'] == 0) return 1;
if ($a['id'] == $b['parent_id']) return -1;
if ($b['id'] == $a['parent_id']) return 1;
return 0;
}
usort($arr, 'compare');
print_r($arr);
output:
Array
(
[0] => Array
(
[id] => 1723
[parent_id] => 0
)
[1] => Array
(
[id] => 456
[parent_id] => 1723
)
[2] => Array
(
[id] => 1203
[parent_id] => 456
)
)
I dont see whats the criteria you want to use to sort. Anyway, you could use uasort function , in which you pass a custom function as argument, so in that function you can define whatever criteria you want to order your array. That function would receive 2 arguments (the 2 variables to compare), and you could compare both parent_id (or whatever is you want to compare). To learn what your custom function should return, check this out.
By using uasort instead of usort you can keep your array indexes (as you said in your example).
精彩评论