array_multisort 与多维对象数组 [英] array_multisort with multi-dimensional object array

查看:40
本文介绍了array_multisort 与多维对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

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

代码如下,以last_name为键的姓的键/值对:

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

推荐答案

为您希望排序的每一列定义一个数组,并使用对象引用语法添加列值:

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

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

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

这篇关于array_multisort 与多维对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆