Mulan
Mulan

Reputation: 135227

How to sort multidimensional array and preserve keys in PHP?

I have two arrays that I need to sort A->Z but all numerical indexes need to be preserved. I have no idea how to approach this problem.

Note: In the $complex array, the order of the subarrays does not matter as long as their associated key is preserved and the subarray contents are sorted.

All keys must be preserved in both examples.

<?php

$simple = array(
    20 => 'Hello',
    10 => 'Cat',
    30 => 'Dog'
);


$complex = array(
    30 => array(
        5 => 'foo',
        10 => 'bar'
        ),
    10 => array(
        4 => 'a',
        1 => 'b'
        ),
    20 => array()
);

desired output

// simple
array(
    10 => Cat,
    30 => Dog,
    20 => Hello
)

// complex; order of top-level indexes (30, 10, and 20) is not important but the key *must* be preserved
array(
    30 => array(
        10 => bar,
        5 => foo,
        ),
    10 => array(
        4 => a,
        1 => b,
        ),
    20 => array()
)

Upvotes: 1

Views: 2615

Answers (2)

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15301

asort

$simple = array(
    20 => 'Hello',
    10 => 'Cat',
    30 => 'Dog'
);
asort($simple);

$complex = array(
    30 => array(
        5 => 'foo',
        10 => 'bar'
        ),
    10 => array(
        4 => 'a',
        1 => 'b'
        ),
    20 => array()
);
array_walk($complex, 'asort');
print_r($complex);

Upvotes: 5

Jacob Pollack
Jacob Pollack

Reputation: 3751

I believe this is what you are looking for, the PHP 'asort' method:

http://php.net/manual/en/function.asort.php

Upvotes: 0

Related Questions