Reputation: 135227
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()
);
// 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
Reputation: 15301
$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
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