2

I want to sort a multi-dimensional array in which each array is an object. The example at

http://php.net/manual/en/function.array-multisort.php

indicates the need to create an array of the columns on which to sort

foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $edition[$key] = $row['edition'];
}

array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);

but I get the followiwng error if I format my request in this format:

Catchable fatal error: Object of class stdClass could not be converted to string

Code is as follows with a key/value pair for last name with key last_name:

foreach ($mw_users as $key => $value) {
$last_name[$key]  = $row['last_name'];
}

array_multisort($last_name, SORT_ASC, $mw_users);
6
  • You can't sort objects, you need to sort on a number or string. Commented Apr 24, 2013 at 18:32
  • I want to sort on one element in the object in this case the last_name Commented Apr 24, 2013 at 18:47
  • Found the answer - define an array for each column you wish to sort by and add the column values using the object reference syntax: foreach ($mw_users as $mw_user) { $lastnames[] = $mw_user->last_name; $firstnames[] = $mw_user->first_name; } array_multisort($lastnames, SORT_ASC, $firstnames, SORT_ASC, $mw_users); Commented Apr 24, 2013 at 19:15
  • If that works, then please post your answer in the answer section for posterity. Commented Apr 24, 2013 at 19:42
  • am not able to for another 7 hours according to stackoverflow but shall do then. Commented Apr 24, 2013 at 19:59

2 Answers 2

2

Define an array for each column you wish to sort by and add the column values using the object reference syntax:

// Obtain a list of columns
foreach ($mw_users as $mw_user) {
    $lastnames[]  = $mw_user->last_name;
    $firstnames[] = $mw_user->first_name;
}

// Sort the data with volume descending, edition ascending
// Add $mw_users as the last parameter, to sort by the common key
array_multisort($lastnames, SORT_ASC, $firstnames, SORT_ASC, $mw_users);

It's similar to sorting database results: http://php.net/...array-multisort.php....

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

Comments

0

When sorting arrays of objects in PHP, it helps to override __tostring() magic method. That way the various sort methods perceive the object as something comparable. For example, a staff object could output the name, or staff id of that staff member.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.