1

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:

array   
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

2
  • So if I understand correctly, you are trying to sort it so that the parent_id is the preceding id? How are you determining what should be the initial ID to start cascading from? Commented Jan 26, 2011 at 22:51
  • Sorry for my late reply. But yeah the initial id would be the one that doesn't have a parent id. Picture it as a tree. If an array doesn't have a parent_id then it's the root basically. Commented Jan 27, 2011 at 14:04

2 Answers 2

1

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
        )

)
Sign up to request clarification or add additional context in comments.

Comments

0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.