【问题标题】:array_multisort with multi-dimensional object arrayarray_multisort 与多维对象数组
【发布时间】:2013-04-18 10:36:24
【问题描述】:

我想对一个多维数组进行排序,其中每个数组都是一个对象。示例在

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

但是如果我以这种格式格式化我的请求,我会收到以下错误:

可捕获的致命错误:stdClass 类的对象无法转换为字符串

代码如下,其中姓氏的键/值对带有键 last_name:

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

array_multisort($last_name, SORT_ASC, $mw_users);

【问题讨论】:

  • 不能对对象进行排序,需要按数字或字符串排序。
  • 我想对对象中的一个元素进行排序,在这种情况下是 last_name
  • 找到答案 - 为您希望排序的每一列定义一个数组,并使用对象引用语法添加列值:foreach ($mw_users as $mw_user) { $lastnames[] = $mw_user ->姓氏; $firstnames[] = $mw_user->first_name; } array_multisort($lastnames, SORT_ASC, $firstnames, SORT_ASC, $mw_users);
  • 如果可行,请将您的答案发布在答案部分以供后代使用。
  • 根据stackoverflow,我不能再过7个小时,但应该这样做。

标签: php object multidimensional-array


【解决方案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...

【讨论】:

    【解决方案2】:

    在 PHP 中对对象数组进行排序时,重写 __tostring() 魔术方法会有所帮助。这样,各种排序方法将对象视为可比较的对象。例如,员工对象可以输出该员工的姓名或员工 ID。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-09
      • 1970-01-01
      • 1970-01-01
      • 2015-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多