简体   繁体   English

如何根据对象属性对对象的二维数组进行排序

[英]How to sort 2D array of objects according to the object property

I've a 2D array like this我有一个像这样的二维数组

$myArray = [
    0=>$Object,
    1=>$Object,
    2=>$Object,
    3=>$Object,
//etc...
]

Each objects has properties and some of them have the same name for example.每个对象都有属性,例如,其中一些具有相同的名称。 How can I sort my Array so that objects with the same name follow each other and only if there is no other objects with the same name property, I go to the next name ?如何对我的 Array 进行排序,以便具有相同名称的对象相互跟随,并且仅当没有其他具有相同名称属性的对象时,我才会转到下一个名称?

$myArray = [
//Objects with the first name
    0=>$Object,
    1=>$Object,
    2=>$Object,
//Objects with the second name
    3=>$Object,
    4=>$Object,
//Objects with the third name
    5=>$Object,
// etc.
]

The array is generated from database so it will never have the same size and the number of objects with a name can be one or more.该数组是从数据库生成的,因此它永远不会具有相同的大小,并且具有名称的对象数量可以是一个或多个。

You can use usort() with anonymous function as below:您可以将usort()匿名函数一起使用,如下所示:

usort($dataArray, function($a, $b) {return strcmp($a->name, $b->name);});

or this:或这个:

function cmp($a, $b) {
    return strcmp($a->name, $b->name);
}

usort($dataArray, "cmp");

This will sort your data objects with property name with their values.这将使用属性name及其值对数据对象进行排序。

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM