1

I have this array for example:

$exampleArray = array (
                    array( 'Name' => 'Opony', 'Kod' =>'OPO',  'Price' => 100 ),
                    array( 'Kod' =>'OLE', 'Name' => 'Olej', 'Price' => 20 ),
                    array( 'Kod' =>'ABC', 'Price' => 20, 'Name' => 'abcdefg' )
                )

Keys in sub array are in random order. I want to sort the sub arrays by key:

Array
(
    [0] => Array
        (
            [Kod] => OPO
            [Name] => Opony
            [Price] => 100
        )
    [1] => Array
       (
            [Kod] => OLE
            [Name] => Olej
            [Price] => 20
       )

I try this:

function compr($x,$y){
  if($x == $y)
     return 0;
  elseif($x>$y)
     return 1;
  elseif($x<$y)
    return-1;
}

uksort($exampleArray, 'compr');

print_r($exampleArray);

But this code doesn't give me my expected result, what is wrong, how can I solve it?

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Marcin Jaworski
  • 330
  • 2
  • 9
  • The keys of that array are 0, 1, 2. I suspect uksort is not the function you want. – IMSoP May 16 '15 at 09:11
  • possible duplicate of [Reference: all basic ways to sort arrays and data in PHP](http://stackoverflow.com/questions/17364127/reference-all-basic-ways-to-sort-arrays-and-data-in-php) – IMSoP May 16 '15 at 09:13
  • Ohh my poor english :(. I want to know how to use uksort() on multidemension arrays. – Marcin Jaworski May 16 '15 at 09:21
  • @MarcinJaworski Show your attempt how you tried to use `uksort`. Also add what your expected output would be – Rizier123 May 16 '15 at 09:36

2 Answers2

2

This should work for you:

Just loop through all of your inner Arrays by reference and then just use uksort() with strcasecmp() to sort your inner Arrays by the keys.

foreach($exampleArray as &$v) {
    uksort($v, function($a, $b){
        return strcasecmp($a, $b);
    });
}

unset($v); //So if you use $v later it doesn't change the last element of the array by reference

output:

Array
(
    [0] => Array
        (
            [Kod] => OPO
            [Name] => Opony
            [Price] => 100
        )
    //...
    [2] => Array
        (
            [Kod] => ABC
            [Name] => abcdefg
            [Price] => 20
        )

)
Rizier123
  • 58,877
  • 16
  • 101
  • 156
0

There is ABSOLUTELY no reason to call a user-defined sorting algorithm (uksort()) here.

Just call ksort() on each row.

Code: (Demo)

foreach ($array as &$row) {
    ksort($row);
}
var_export($array);

Or (Demo)

array_walk($array, fn(&$row) => ksort($row));
var_export($array);

Or (Demo)

function keySortRow(array $row): array {
    ksort($row);
    return $row;
}

var_export(
    array_map('keySortRow', $array)
);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136