Home > Backend Development > PHP Tutorial > How to Sort a Multi-Dimensional PHP Array by an Inner Array Value?

How to Sort a Multi-Dimensional PHP Array by an Inner Array Value?

DDD
Release: 2024-11-03 06:21:03
Original
765 people have browsed it

How to Sort a Multi-Dimensional PHP Array by an Inner Array Value?

Sorting a Multi-Dimensional PHP Array by an Inner Array Value

To sort a multi-dimensional PHP array based on a specific value in the inner array, you can employ a custom sorting function.

Custom Sorting Function:

<code class="php">function array_sort($array, $on, $order = SORT_ASC) {
    $new_array = [];
    $sortable_array = [];

    if (count($array) > 0) {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                foreach ($value as $key2 => $value2) {
                    if ($key2 == $on) {
                        $sortable_array[$key] = $value2;
                    }
                }
            } else {
                $sortable_array[$key] = $value;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
                break;
            case SORT_DESC:
                arsort($sortable_array);
                break;
        }

        foreach ($sortable_array as $key => $value) {
            $new_array[$key] = $array[$key];
        }
    }

    return $new_array;
}</code>
Copy after login

Usage:

<code class="php">$list = array(
    array('type' => 'suite', 'name' => 'A-Name'),
    array('type' => 'suite', 'name' => 'C-Name'),
    array('type' => 'suite', 'name' => 'B-Name')
);

$list = array_sort($list, 'name', SORT_ASC);

print_r($list);</code>
Copy after login

Output:

<code class="php">array(3) { [0]=> array(2) { ["type"]=> string(5) "suite" ["name"]=> string(6) "A-Name"    } [2]=> array(2) { ["type"]=> string(5) "suite" ["name"]=> string(6) "B-Name" } [1]=> array(2) { ["type"]=> string(5) "suite" ["name"]=> string(6) "C-Name" } }</code>
Copy after login

The above is the detailed content of How to Sort a Multi-Dimensional PHP Array by an Inner Array Value?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template