Hướng dẫn php sort array column

To sort on one column of values, a combination of array_column() and array_multisort() is one sensible way. Demo

Nội dung chính

  • How do you sort an array of objects by property in PHP?
  • Can we sort array of objects?
  • How do you sort an array of elements?
  • How do you sort an array of arrays in PHP?

array_multisort(array_column($array, 'count'), $array);

Or only call upon usort() with the spaceship operator to perform less iterating in this scenario. Demo

usort($array, fn($a, $b) => $a->count <=> $b->count);

Notice that although the count values are cast as string type values in the input array, both sorting functions will correctly sort the values numerically instead of alphabetizing them (erroneously putting 23420 before `420). This is a reliable default feature.

Even if you are variably declaring the column to sort on, both approaches allow the variable to be used without any addition techniques.

Multisort Demo with variable

$property = 'count';
array_multisort(array_column($array, $property), $array);

Usort Demo with variable

$property = 'count';
usort($array, fn($a, $b) => $a->$property <=> $b->$property);

Both native sorting functions modify by reference, so do not try to access the sorted array by their return value.

array_multisort()'s default sorting direction is ascending, so it is of no benefit to explicitly use the SORT_ASC between the two array parameters. If descending sorting is desired, write SORT_DESC between the two arrays (as the second parameter).

usort() will sort ascending when the custom function body puts $a data on the left side of the spaceship operator and $b data on the right side. For sorting in a descending direction, just write $b data on the left and $a data on the right.

Both approaches are capable of receiving multiple sorting rules, but because this question only asks to sort on a single column, that guidance is inappropriate here.

It will be less efficient to call a function (like strcmp()) on every iteration while sorting. This is no longer best practice. Neither is using a two-way comparison (like > or <) to return a boolean outcome. A three-way comparison is expected from usort().

For sorting data with multiple rules/columns/properties, this answer gives good guidance.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given an array of objects and the task is to sort the array by object by given fields.

    Approach:
    The usort() function is an inbuilt function in PHP which is used to sort the array of elements conditionally with a given comparator function. The usort() function can also be used to sort an array of objects by object field. Call usort() function with first argument as the array of objects and second argument as the comparator function on the basis of which comparison between two array objects has to be made.

    Example:

    $gfg_array = array(

        array(

            'score' => '100',

            'name' => 'Sam',

            'subject' => 'Data Structures'

        ),

        array(

            'score' => '50',

            'name' => 'Tanya',

            'subject' => 'Advanced Algorithms'

        ),

        array(

            'score' => '75',

            'name' => 'Jack',

            'subject' => 'Distributed Computing'

        )

    );

    class geekSchool {

        var $score, $name, $subject;

        public function geekSchool($data) {

            $this->name = $data['name'];

            $this->score = $data['score'];

            $this->subject = $data['subject'];

        }

    }

    function data2Object($data) {

        $class_object = new geekSchool($data);

        return $class_object;

    }

    function comparator($object1, $object2) {

        return $object1->score > $object2->score;

    }

    $school_data = array_map('data2Object', $gfg_array);

    print("Original object array:\n");

    print_r($school_data);

    usort($school_data, 'comparator');

    print("\nSorted object array:\n");

    print_r($school_data);

    ?>

    Output:

    Original object array:
    Array
    (
        [0] => geekSchool Object
            (
                [score] => 100
                [name] => Sam
                [subject] => Data Structures
            )
    
        [1] => geekSchool Object
            (
                [score] => 50
                [name] => Tanya
                [subject] => Advanced Algorithms
            )
    
        [2] => geekSchool Object
            (
                [score] => 75
                [name] => Jack
                [subject] => Distributed Computing
            )
    
    )
    
    Sorted object array:
    Array
    (
        [0] => geekSchool Object
            (
                [score] => 50
                [name] => Tanya
                [subject] => Advanced Algorithms
            )
    
        [1] => geekSchool Object
            (
                [score] => 75
                [name] => Jack
                [subject] => Distributed Computing
            )
    
        [2] => geekSchool Object
            (
                [score] => 100
                [name] => Sam
                [subject] => Data Structures
            )
    
    )
    

    How do you sort an array of objects by property in PHP?

    Approach: The usort() function is an inbuilt function in PHP which is used to sort the array of elements conditionally with a given comparator function. The usort() function can also be used to sort an array of objects by object field.

    Can we sort array of objects?

    We can sort an array of objects in JavaScript by using our built-in Arrays. sort() method, however, we must pass a custom function to our built-in sort method. The function is needed for the comparison of the properties based on which we want to sort our array of objects.

    How do you sort an array of elements?

    The array can be sorted in ascending order by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning..

    Selection Sort..

    Bubble Sort..

    Merge Sort..

    Radix Sort..

    Insertion Sort, etc..

    How do you sort an array of arrays in PHP?

    To PHP sort array by key, you should use ksort() (for ascending order) or krsort() (for descending order). To PHP sort array by value, you will need functions asort() and arsort() (for ascending and descending orders).