Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort dependent child array in php

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
    ))
like image 516
Sanjay Avatar asked Dec 11 '15 10:12

Sanjay


1 Answers

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.

like image 192
rajausman haider Avatar answered Nov 01 '22 10:11

rajausman haider