Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End Sort array with uasort()

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #194355
    justdan
    Participant

    Hi guys. I’m working on a little PHP function that will sort an array based off of if the item returned is “verified” or not. I’m not very familiar with PHP and I’ve been doing a lot of reading up since I figured there could possibly be a method to make this easier. Reading around it sounded like the uasort() was what I needed for its sorting abilities and that it maintains index association, but I’m a little confused as how to properly use it. The original block of PHP I am working on looks like this:

    `<?php
    if (count($results)):

        $lexisIndex = 1;
    
        foreach ($results as $person){
            $person-&gt;isVerified = (substr($person-&gt;first_name, 0, 1) ==  substr($fname, 0, 1) &amp;&amp; $person-&gt;last_name == $lname );
            $person-&gt;lexisIndex = $lexisIndex++;
        }
    
        foreach ($results as $person):
    

    ?>
    `

    From here I added the sortIt function, put the results into an array, and then sort from that array like this:

    `<?php
    if (count($results)):

    $lexisIndex = 1;
    
    foreach ($results as $person){
        $person-&gt;isVerified = (substr($person-&gt;first_name, 0, 1) ==  substr($fname, 0, 1) &amp;&amp; $person-&gt;last_name == $lname );
        $person-&gt;lexisIndex = $lexisIndex++;
    }
    
    function sortIt($a, $b) {
        if ($a == $b) {
            return 0;
        }
        return ($a &lt; $b) ? -1 : 1;
    }                               
    
    $array = array($results);
    uasort($array, 'sortIt');
    
    foreach ($results as $person):
    

    ?>
    `

    Where I’m stumped is that part where I can get the function to compare the $a and $b to see if each person “isVerified” or not. If they are, I would like these people to display at the top of the list. Any help I can get to give me a nudge in the right direction is always appreciated. Thanks guys.

    #194369
    Anonymous
    Inactive

    $a and $b are values from the array. In this case, person objects. isVerified is either true or false, right?

    function sortIt($a, $b) {
        return $a-&gt;isVerified - $b-&gt;isVerified;
    }
    
Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘Back End’ is closed to new topics and replies.