I want to sort array based on child values, I want parent child array at first position then its child and then its grand child and so on... based on its "Parent" value here is my example array,
$array= Array(
Array("self"=>"user4", "parent"=>"user6"),
Array("self"=>"user2", "parent"=>"user1"),
Array("self"=>"user1", "parent"=>"user4"),
Array("self"=>"user5", "parent"=>"user2"),
Array("self"=>"user6", "parent"=>"user3"),
Array("self"=>"user3", "parent"=>"Parent") // it will be anything
);
this array should be sorted like below
Array(
[0] => Array
(
[self] => user3
[parent] => Parent
)
[1] => Array
(
[self] => user6
[parent] => user3
)
[2] => Array
(
[self] => user4
[parent] => user6
)
[3] => Array
(
[self] => user1
[parent] => user4
)
[4] => Array
(
[self] => user2
[parent] => user1
)
[5] => Array
(
[self] => user5
[parent] => user2
))
You can use it in the following way:
$array= Array(
Array("self"=>"user4", "parent"=>"user6"),
Array("self"=>"user2", "parent"=>"user1"),
Array("self"=>"user1", "parent"=>"user4"),
Array("self"=>"user5", "parent"=>"user2"),
Array("self"=>"user6", "parent"=>"user3"),
Array("self"=>"user3", "parent"=>"Parent") // it will be anything
);
$result = "";
foreach($array as $val)
{
if($val['parent']== 'Parent')
{
$result[] = $val;
getNextNode($val['self']);
}
}
function getNextNode($child)
{
global $array;
global $result;
foreach($array as $val)
{
if($val['parent'] == $child)
{
$result[] = $val;
getNextNode($val['self']);
}
}
}
echo "<pre/>";
print_r($result);
You get the desired result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With