Answers for "php sort array by object value"

PHP
1

php sort array by object value

/**
 * A generic PHP sorting algorithm that uses `usort` and `strcmp`.
 * `usort` — Sort an array by values using a user-defined comparison function.
 * `strcmp` — Returns < 0 if param 1 is less than param 2; > 0 if param 1 is greater than param 2, and 0 if they are equal.
 */
$questions = [
  { id: 1, ordinal: 55 },
  { id: 2, ordinal: 67 },
  { id: 3, ordinal: 32 },
];

function sortByOrdinal($param1, $param2) {
    return strcmp($param1->ordinal, $param2->ordinal);
}

/* `usort` alters an existing array. */
usort($questions, "sortByOrdinal");

/**
 * $questions = [
 *   { id: 3, ordinal: 32 },
 *   { id: 1, ordinal: 55 },
 *   { id: 2, ordinal: 67 },
 * ];
 */
Posted by: Guest on September-02-2020
1

php sort array of objects

<?php
class Person {
    var $first_name;
    var $last_name;

    function __construct( $fn, $ln ) {
        $this->first_name = $fn;
        $this->last_name = $ln;
    }

    public function get_first_name() {
        return $this->first_name;
    }

    public function get_last_name() {
        return $this->last_name;
    }
}

$rob = new Person( 'Rob', 'Casabona' );
$joe = new Person( 'Joe', 'Casabona' );
$erin = new Person( 'Erin', 'Casabona' );
$steve = new Person( 'Steve', 'Wozniack' );
$bill = new Person( 'Bill', 'Gates' );
$walt = new Person( 'Walt', 'Disney' );
$bob = new Person( 'Bob', 'Iger' );

$people = array( $rob, $joe, $erin, $steve, $bill, $walt, $bob );

//The sorting
usort($people, function($a, $b){
    return [$a->get_last_name(), $a->get_first_name()] <=> [$b->get_last_name(), $b->get_first_name()];   
});

?>

<pre>
    <?php print_r($people);?>
</pre>
Posted by: Guest on July-30-2021

Code answers related to "php sort array by object value"

Browse Popular Code Answers by Language