-2

So i've been looking throughout Stack Overflow looking for a solution for this problem. I have a multidimensional, non associative array in php and i want to sort it by one of its values, while maintaining the rest of the values within the same child array.

In the next example i want to sort the array by $fruits[This value][0].

This is what i have:

$fruits = array
(
array(2, apple),
array(1, orange),
array(4, banana),
array(3, kiwi),
);

This is what im looking for:

$fruits = array
(
array(1, orange),
array(2, apple),
array(3, kiwi),
array(4, banana),
);

This is what i dont want:

$fruits = array
(
array(1, apple),
array(2, orange),
array(3, banana),
array(4, kiwi),
);
Nimantha
  • 6,405
  • 6
  • 28
  • 69
  • Use two http://php.net/manual/en/function.array-map.php and make your custom sorting function – Bdloul May 17 '18 at 22:39
  • FYI, `sort($fruits)` will work for this example. You can read about how arrays are compared to see why: http://php.net/manual/en/language.operators.comparison.php – Don't Panic May 17 '18 at 23:00

1 Answers1

4

You can use array_multisort to sort the array by column 0

array_multisort($fruits, array_column($fruits, 0));

Example: http://sandbox.onlinephpfunctions.com/code/4b8bef53eeb9bf7b1cb93ab93e27de6f7ac60174

apokryfos
  • 38,771
  • 9
  • 70
  • 114