2013-04-24 66 views
1

我想排序一个多维数组,其中每个数组是一个对象。在array_multisort与多维对象数组

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

的例子表明需要创建列的一个阵列上进行排序

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

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

,但我得到了followiwng错误,如果我在这个格式来格式化我的要求:

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

代码如下,键名为键/值对,键名为last_name:

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

array_multisort($last_name, SORT_ASC, $mw_users); 
+0

无法对对象进行排序,您需要对数字或字符串进行排序。 – Revent 2013-04-24 18:32:15

+0

我想排序在这种情况下对象的一个​​元素姓氏 – user2316819 2013-04-24 18:47:03

+0

找到答案 - 定义一个数组,为每个列你想排序并添加使用对象参考语法的列值: 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); – user2316819 2013-04-24 19:15:14

回答

1

定义为要由进行排序和添加使用对象引用语法的列值的每一列数组:

// 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); 

它类似于排序数据库结果:http://php.net/...array-multisort.php...

0

当在PHP中排序对象数组时,它有助于覆盖__tostring()魔术方法。这样,各种排序方法将对象视为可比较的东西。例如,一个员工对象可以输出该员工的姓名或员工编号。