Sorting objects by their property in PHP
Created:10 Dec 2016 13:10:14 , in Web development
Sorting objects by their property..
Prepare some sample objects:
$to_be_sorted = array();
$chars = 'abcdefg';
for($i = 0;$i< 3;$i++ ){
$random_number = rand(1,99);
$to_be_sorted[] = (object) [
'num' => $random_number,
'str' => $chars[$random_number % 7]
];
}
Sort by number
usort($to_be_sorted,function($a,$b){
return $a -> num > $b -> num;
});
Use usort PHP function.
Sort by string
usort($to_be_sorted,function($a,$b){
return (int)strcmp($a -> str,$b -> str);
});
This post was updated on 06 Oct 2021 20:32:14
Author, Copyright and citation
Author
Author of the this article - Sylwester Wojnowski - is a sWWW web developer. He has been writing computer code for the websites and web applications since 1998.
Copyrights
©Copyright, 2024 Sylwester Wojnowski. This article may not be reproduced or published as a whole or in parts without permission from the author. If you share it, please give author credit and do not remove embedded links.
Computer code, if present in the article, is excluded from the above and licensed under GPLv3.
Citation
Cite this article as:
Wojnowski, Sylwester. "Sorting objects by their property in PHP." From sWWW - Code For The Web . https://swww.com.pl//main/index/sorting-objects-by-their-property-in-php
Add Comment