phparrayssortingmultidimensional-array

Sort an object array by a property


There are a bunch of topics on this but none of them are exactly what I need. I have an array with fname, lname, etc. I need to sort by lname using this code:

if ($myvar)
    foreach( $myvar as $key => $row) {
        echo "<p>$row->fname $row->lname";
        echo "$row->intro</p>";
        sort($row->lname);
    }
else 
    echo "<p>No Results for your search.</p>";

You can see I threw in a sort, I've also tried ksort(), but nothing is happening. I tried a couple of other things from this forum, but no luck. Is the order wrong? Is the syntax incorrect?


Solution

  • usort($myvar, function($a,$b) {return strcmp($a->lname, $b->lname);});
    

    Though, as said in the comments, if this is searching over a database or search engine, you're better off letting those sort your stuff.