0

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.

1
  • 1
    You're sorting the sub arrays. You just need the parent array sorted, so ksort() should do the trick. If you awnt the sub-arrays sorted too,t hen you'll need a custom function, which is what usort() is for. Commented Jan 21, 2014 at 15:32

2 Answers 2

1

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
        )

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

Comments

0

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

8 Comments

foreach ($data2 as $k){ needs to be foreach ($data2 as &$k){ :-)
You are right, but would you care to explain? $k is passed as a normal array, no?
@RocketHazmat I am interested in this also.
What do you mean by "normal array"? When you foreach you are operating on a copy of the array. So when you ksort($k), you are sorting it, but you are not updating the original array. &$k makes $k a reference to the element in the original array. Now when you update $k, it's updated in the original array.
@RocketHazmat Thank you for the explanation. Running this code proves you're correct and my answer was updated. Makes sense. I would have used Humble Rat's for as opposed to foreach myself, but I was copying OP's code. Thanks for clarifying.
|

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.