0

I found an array sorting function on the php manual site which does exactly what I want, but it generates warnings and I have been trying to work out why and how to stop them. Any advice much appreaciated.

function fnArrayOrderby(){
//function to sort a database type array of rows by the values in one or more column
//source http://php.net/manual/en/function.array-multisort.php - user notes
//example of use -> $sorted = fnArrayOrderby($data, 'volume', SORT_DESC, 'edition', SORT_ASC);

$args = func_get_args(); //Gets an array of the function's argument list (which can vary in length)
//echo "sorting on ".$args[1];
$data = array_shift($args); //Shift an element off the beginning of array
foreach ($args as $n => $field) {
    if (is_string($field)) {
        $tmp = array();
        foreach ($data as $key => $row)
            $tmp[$key] = $row[$field];
        $args[$n] = $tmp;
        }
}
$args[] = &$data;
call_user_func_array('array_multisort', $args);
 return array_pop($args);
}

the warnings generated are

  • PHP Warning: Invalid argument supplied for foreach() in .. for the line " foreach ($data as $key => $row)"
  • PHP Warning: array_multisort(): Argument #5 is expected to be an array or a sort flag ... for the line call_user_func_array('array_multisort', $args)
9
  • 4
    array_shift doesn't return an array Commented Jun 13, 2016 at 22:09
  • 2
    @tkausl: Unless the value in the array happens to be an array. Commented Jun 13, 2016 at 22:10
  • Right, let me rephraze it: array_shift does not return the array passed and shifted but the value which got shifted out of the passed array. This function takes the array by-reference, so the original array gets changed. Commented Jun 13, 2016 at 22:12
  • 1
    From php.net/manual/en/function.array-multisort.php#100534 ? Commented Jun 13, 2016 at 22:27
  • 1
    Could we see the whole thing - as the args passed in are relevant -- or are you callins as per the 'example of use'? Commented Jun 13, 2016 at 22:29

1 Answer 1

0

I have now worked it out - thanks to the comments, especially from @rivimey which made me realise there probably wasn't anything wrong with the function itself but rather with the way it was being called. It turned out the warnings were being generated when the function was applied to an array which was not set. For example I use the function to sort the array of images associated with a database entry, but if there are no images then the array is not set. So I have now added the following line to the function if (!isset($args[0])) { return;}
Thanks for the help!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.