2

I have this array:

$array["4E-952778"][0]['fileName'] = "File 1";
$array["4E-952778"][0]['product'] = "Muse On Demand";
$array["4E-952778"][1]['fileName'] = "File 2";
$array["4E-952778"][1]['product'] = "Muse On Demand";   

$array["15210"][0]['fileName'] = "File 3";
$array["15210"][0]['product'] = "4Manager"; 
$array["15210"][1]['fileName'] = "File 4";
$array["15210"][1]['product'] = "4Manager";

$products = array();
foreach ($array as $key => $row) {
    $products[$key] = $row[0]['product'];       
}
array_multisort($products, SORT_ASC, $array);

print_r($array);

and the result is this :

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [fileName] => File 3
                    [product] => 4Manager
                )

            [1] => Array
                (
                    [fileName] => File 4
                    [product] => 4Manager
                )

        )
    [4E-952778] => Array
        (
            [0] => Array
                (
                    [fileName] => File 1
                    [product] => Muse On Demand
                )
            [1] => Array
                (
                    [fileName] => File 2
                    [product] => Muse On Demand
                )
        )
)

As you can observe the function array_multisort() change the key: 15210 to 0 why this change?

Rizier123
  • 58,877
  • 16
  • 101
  • 156
ihssan
  • 369
  • 1
  • 6
  • 24

2 Answers2

4

A quote from the manual:

Associative (string) keys will be maintained, but numeric keys will be re-indexed.

And PHP is automatically casting your string "15210" to an integer.

The trick for that to work is to add a "0" to the key ("015210"), it will force the type casting to (string).

If want to read more about this see: Bug #21788 array_multisort() changes array keys unexpectedly given numeric strings as keys

Akram Fares
  • 1,653
  • 2
  • 17
  • 32
  • the problem is that i can't modify the keys – ihssan Apr 03 '15 at 16:06
  • Well a nice little trick I wasn't aware of until know, but sadly it doesn't solve OP's problems – Rizier123 Apr 03 '15 at 16:09
  • I can tell you to perform a loop on the array and check for every item before you make the sorting. But it's not a good solution i think. Can you tell us why you can't modify the keys? – Akram Fares Apr 03 '15 at 16:14
  • because after that i should print the keys with the values and it should be 15210 and not 015210 – ihssan Apr 03 '15 at 16:24
  • Simple, after you sort your keys, you replace them another time to get the initial values. If you don't have performance constraints go for it. – Akram Fares Apr 03 '15 at 16:25
  • that's not a solution for my project, it should be done efficiently – ihssan Apr 03 '15 at 16:28
0

i found a solution to this problem

uasort($array, function ($a, $b) {
 $i=0;
 return strcmp($a[$i]['product'], $b[$i]['product']);

});

ihssan
  • 369
  • 1
  • 6
  • 24