mansoondreamz
mansoondreamz

Reputation: 493

How to sort mutidimensional array by its key in php

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

Answers (2)

The Humble Rat
The Humble Rat

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

Dutchie432
Dutchie432

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

Related Questions