1

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()
)
1

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

2 Comments

@naomik added code examples for both simple and complex. for complex use array_walk to iterate over the array which will call asort over each sub-array.
0

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

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

1 Comment

Pointing someone to the php manual can be done as a comment under the question instead of posting an answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.