I want to sort a tree hierarchy array with structure as below based on a key (in this example: timestamp).
$topics = array(
array('name' => 'n1', 'timestamp' => 5000, 'children' => array()),
array('name' => 'n2', 'timestamp' => 4000, 'children' => array(
array('name' => 'n3', 'timestamp' => 6000, 'children' => array()),
array('name' => 'n4', 'timestamp' => 2000, 'children' => array(
array('name' => 'n5', 'timestamp' => 4000, 'children' => array()),
array('name' => 'n6', 'timestamp' => 3000, 'children' => array())
)),
)),
array('name' => 'n7', 'timestamp' => 1000, 'children' => array())
);
My sort function:
function sequenceSort(&$a, &$b) {
if (!empty($a['children'])) {
usort($a['children'], 'sequenceSort');
}
if ($a['timestamp'] == $b['timestamp']) {
return 0;
}
return $a['timestamp'] < $b['timestamp'] ? -1 : 1;
}
usort($topics, 'sequenceSort');
print_a($topics);
At some levels it produces the correct output, at another it doesn't, e.g:
1000 ✔
4000 ✔
6000 ✘
2000 ✘
4000 ✘
3000 ✘
5000 ✔
What's wrong with this?
usort