Reputation: 493
I have a mutidimensional array something like this
<?php
$data2[3][1]=6;
$data2[9][3]=4;
$data2[9][2]=18;
$data2[4][2]=24;
$data2[4][0]=12;
$data2[4][1]=14;
?>
I want to sort this array by its key, so that it looks like this
$data2[3][1]=6;
$data2[4][0]=12;
$data2[4][1]=14;
$data2[4][2]=24;
$data2[9][2]=18;
$data2[9][3]=4;
used this
foreach ($data2 as $k[]){
ksort($k);
}
print_r($k);
but not working.
Upvotes: 0
Views: 595
Reputation: 4696
The loop is necessary for the next level down
$data2[3][1]=6;
$data2[9][3]=4;
$data2[9][2]=18;
$data2[4][2]=24;
$data2[4][0]=12;
$data2[4][1]=14;
foreach($data2 as $key=>$data)
{
ksort($data2[$key]);
}
ksort($data2);
echo '<pre>';
print_r($data2);
echo '</pre>';
This will output
Array
(
[3] => Array
(
[1] => 6
)
[4] => Array
(
[0] => 12
[1] => 14
[2] => 24
)
[9] => Array
(
[2] => 18
[3] => 4
)
)
Upvotes: 1
Reputation: 29160
I think you want to first sort the array, then the sub-arrays within.
ksort($data2); //Sort Array
foreach ($data2 as &$k){
ksort($k); //Sort Each Sub-Array
}
Updated based on Rocket Hazmat's comment
Upvotes: 0