简体   繁体   中英

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 ?

$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($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.

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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