Search code examples
phplistsortingarray-multisort

PHP array_multisort throws error


I am new to PHP and trying to sort a list of associative arrays. I want to sort them on a family field, just a string, in descending order. Whenever I try to sort the associative array ... array, it gives me this error.

Warning: array_multisort(): Argument #1 is expected to be an array or a sort flag.

PHP Code

<?php

$allColors = array(
  '0' => array(
  "id"=> "1",
  "family"=> "blue",
  "name"=> "ariel blue",
  "hex"=> "#339FFF"),

 '3' => array(
  "id"=> "3",
  "family"=> "green",
  "name"=> "forest",
  "hex"=> "#FAFF33"),

 '1' => array(
  "id"=> "2",
  "family"=> "blue",
  "name"=> "aqua marine",
  "hex"=> "#339FFF"),

 '4' => array(
  "id"=> "4",
  "family"=> "green",
  "name"=> "lime",
  "hex"=> "#FAFF33"),

 '2' => array(
  "id"=> "5",
  "family"=> "blue",
  "name"=> "teal",
  "hex"=> "#339FFF"),

 '5' => array(
  "id"=> "6",
  "family"=> "green",
  "name"=> "yellow-green",
  "hex"=> "#FAFF33")
); 

array_multisort($family, SORT_DESC, $allColors);

?> 

Solution

  • If you are trying to sort the array by "family", then the first parameter to array_multisort needs to be the contents of your "family" column.

    array_multisort( array_column( $allColors, 'family' ), SORT_DESC, $allColors );