How to Sort a Multidimensional Array by Key: A Step-by-Step Solution?

Barbara Streisand
Release: 2024-10-20 19:02:02
Original
579 people have browsed it

How to Sort a Multidimensional Array by Key: A Step-by-Step Solution?

Sorting a Multidimensional Array by Key: A Comprehensive Guide

Arranging the elements of a multidimensional array in a specific order can be a common requirement in programming. Sorting by a particular key provides an efficient way to organize and retrieve data.

Consider the following multidimensional array containing invitations:

Array (
[0] => Array
    (
        [iid] => 1
        [invitee] => 174
        [nid] => 324343
        [showtime] => 2010-05-09 15:15:00
        [location] => 13
        [status] => 1
        [created] => 2010-05-09 15:05:00
        [updated] => 2010-05-09 16:24:00
    )

[1] => Array
    (
        [iid] => 1
        [invitee] => 220
        [nid] => 21232
        [showtime] => 2010-05-09 15:15:00
        [location] => 12
        [status] => 0
        [created] => 2010-05-10 18:11:00
        [updated] => 2010-05-10 18:11:00
    ))
Copy after login

To sort this array by the "status" key, we can employ the usort() function and a custom comparison function.

Custom Comparison Function

The comparison function determines the order of the elements by comparing their keys. Here's a function that compares based on the "status" key:

function cmp($a, $b) {
    if ($a['status'] == $b['status']) {
        return 0;
    }
    return ($a['status'] < $b['status']) ? -1 : 1;
}
Copy after login

This function returns -1 when $a should come before $b, 1 when $a should come after $b, and 0 when they are equal.

Sorting the Array

We can now sort the array using usort():

usort($array, "cmp");
Copy after login

This will sort the array by the "status" key in ascending order. If we want to reverse the order, we can use rsort():

rsort($array, "cmp");
Copy after login

By utilizing the provided comparison function and sorting functions, we can effortlessly sort multidimensional arrays by any desired key.

The above is the detailed content of How to Sort a Multidimensional Array by Key: A Step-by-Step Solution?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!