2

I have this multidimensional array:

$value = [
    'name' => ['silverado', 'civic'],
    'type' => ['truck', 'car'],
];

I want to basically sort both of these child arrays by the values of name, ascending.

I have this code, which works:

$value = [
    'name' => ['silverado', 'civic'],
    'type' => ['truck', 'car'],
];
$name_type = [];
$columns = [];

foreach ($value['name'] as $k => $v) {
    $name_type[$v] = $value['type'][$k];
}

ksort($name_type);

foreach ($name_type as $name => $type) {
    $columns['name'][] = $name;
    $columns['type'][] = $type;
}

$value = $columns;

I'm just curious if there is a better way of coding this rather than using 2 foreach loops.

LF00
  • 27,015
  • 29
  • 156
  • 295
kdion4891
  • 1,169
  • 12
  • 17
  • You accept the wrong answer. It's [this result](https://3v4l.org/oLVbq) you want ? Certainly not. You want to sort on name, not on name and type seperately. – LF00 Sep 16 '19 at 07:03
  • Your answer does not even work. Notice how in the 2nd array of your solution, they are not sorted appropriately. A `civic` is not a `truck`. Anant's answer worked perfectly. – kdion4891 Sep 16 '19 at 07:12
  • The 2nd array is sort on the name. Have you check the link in my comment above. Is that order you wanted.Which output is different with your code. Check it, [your code result](https://3v4l.org/0YlET) and [Anant's code result](https://3v4l.org/oLVbq) – LF00 Sep 16 '19 at 07:34
  • And the `$value` have different order, in your question. The first have type `'type' => ['car', 'truck'],` and the second have `'type' => ['truck', 'car'],` – LF00 Sep 16 '19 at 07:40
  • I use the 1st `$value` in your question, so I have different order. Pleast edit you question, and make the two `$value` with same value. – LF00 Sep 16 '19 at 07:43
  • It's weird because Anant's code, while not working on that website, works fine in my actual app... – kdion4891 Sep 16 '19 at 08:19
  • 1
    Anant's code sort name and type seperately. While your code sort type and name both on the order of name column. – LF00 Sep 16 '19 at 08:21
  • You were right all along. I updated the accepted answer. – kdion4891 Sep 16 '19 at 08:27
  • Related, highly-dynamic approach https://stackoverflow.com/q/11108891/2943403 – mickmackusa Jul 29 '22 at 12:28

1 Answers1

1

You can use array_multisort, check Demo

array_multisort($value["name"],$value["type"]);
LF00
  • 27,015
  • 29
  • 156
  • 295