Potato
Potato

Reputation: 3

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?

Upvotes: 0

Views: 144

Answers (2)

Juan de Parras
Juan de Parras

Reputation: 778

In your code seems like you have an array of arrays. If you have only one array, you dont need use sort inside the foreach. Sort - Sort an array, so use it directly like this:

if ($myvar) {
   uasort($myvar, function($a,$b) {return strcmp($a->lname, $b->lname);}));
}else{
    echo "<p>No Results for your search.</p>";
}

Upvotes: 0

fd8s0
fd8s0

Reputation: 1927

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.

Upvotes: 1

Related Questions