🐶
PHP

Sort Multidimensional Arrays by Value in PHP

By Filip on 10/17/2024

Learn how to efficiently sort multi-dimensional arrays in PHP by specific values within the nested structures.

Sort Multidimensional Arrays by Value in PHP

Table of Contents

Introduction

In PHP, sorting a multi-dimensional array based on the values of a specific key can be achieved using a combination of the array_multisort() and array_column() functions. This approach allows you to order the array elements according to the values associated with the chosen key.

Step-by-Step Guide

To sort a multi-dimensional array in PHP by the values of a specific key, you can use the array_multisort() function in conjunction with array_column().

  1. Extract the values from the specific key:

    $sortKey = 'name'; // Key to sort by
    $values = array_column($myArray, $sortKey);
  2. Use array_multisort() to sort:

    array_multisort($values, SORT_ASC, $myArray);

Explanation:

  • array_column($myArray, $sortKey) retrieves all values from the specified $sortKey in the multi-dimensional array $myArray.
  • array_multisort() takes the extracted $values as the first argument, followed by the sorting order (SORT_ASC for ascending, SORT_DESC for descending), and finally the original array $myArray.

Example:

$myArray = [
    ['name' => 'Bob', 'age' => 30],
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Charlie', 'age' => 35],
];

$sortKey = 'age';
$values = array_column($myArray, $sortKey);
array_multisort($values, SORT_ASC, $myArray);

print_r($myArray);

This will output the array sorted by age in ascending order.

Code Example

The PHP code sorts a multi-dimensional array called $myArray by the values of a specified key, which is 'age' in this case. It extracts the 'age' values into a separate array, sorts this array in ascending order, and then uses array_multisort() to rearrange the original $myArray based on the sorted 'age' values. The output is the sorted array.

<?php
$myArray = [
    ['name' => 'Bob', 'age' => 30],
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Charlie', 'age' => 35],
];

// Key to sort by
$sortKey = 'age';

// Extract the values for the sorting key
$values = array_column($myArray, $sortKey);

// Sort the array by the extracted values
array_multisort($values, SORT_ASC, $myArray);

// Output the sorted array
print_r($myArray);
?>

Output:

Array
(
    [0] => Array
        (
            [name] => Alice
            [age] => 25
        )

    [1] => Array
        (
            [name] => Bob
            [age] => 30
        )

    [2] => Array
        (
            [name] => Charlie
            [age] => 35
        )

)

Explanation:

  1. $myArray: This is the multi-dimensional array we want to sort.
  2. $sortKey = 'age';: We specify that we want to sort the array by the values of the 'age' key.
  3. $values = array_column($myArray, $sortKey);: This line extracts all the 'age' values from $myArray and stores them in the $values array.
  4. array_multisort($values, SORT_ASC, $myArray);: This is the core sorting function.
    • It takes the $values array (containing the 'age' values) as the first argument. This determines the sorting order.
    • SORT_ASC specifies that we want to sort in ascending order.
    • $myArray is passed as the last argument. array_multisort() will rearrange the elements in $myArray based on the sorting of $values.

After executing this code, $myArray will be sorted by the 'age' values in ascending order.

Additional Notes

  • Flexibility: This method is very flexible. You can:
    • Sort by any key that exists in your sub-arrays.
    • Easily change the sort order (ascending/descending) using SORT_ASC or SORT_DESC.
  • Maintaining Association: array_multisort sorts the $values array and reorders the $myArray elements in the same way. This ensures that the relationship between the sorted values and the original array elements is preserved.
  • Alternative: usort: For more complex sorting logic (e.g., sorting by multiple keys or using custom comparison functions), you can use the usort() function.
  • Performance: While convenient, for very large arrays, using array_column and array_multisort might not be the most performant. Consider alternative sorting algorithms or libraries if performance becomes a bottleneck.
  • Error Handling: It's good practice to check if $sortKey exists in your sub-arrays before using array_column to prevent warnings or errors.
  • PHP Version: array_column was introduced in PHP 5.5.0. If you're using an older version, you'll need to find alternative ways to extract the values for sorting.

Summary

This approach uses array_multisort() and array_column() to sort a multi-dimensional array based on the values of a chosen key.

Steps:

  1. Extract Values: Use array_column($myArray, $sortKey) to get an array of values from the desired key ($sortKey) within the multi-dimensional array ($myArray).

  2. Sort: Utilize array_multisort($values, SORT_ASC, $myArray) to sort. This function takes:

    • $values: The extracted values array.
    • SORT_ASC: Sorting order (ascending in this case, use SORT_DESC for descending).
    • $myArray: The original array, which gets sorted in place.

Example:

Sorting an array of people by their age:

$myArray = [
    ['name' => 'Bob', 'age' => 30],
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Charlie', 'age' => 35],
];

$sortKey = 'age';
$values = array_column($myArray, $sortKey);
array_multisort($values, SORT_ASC, $myArray);

This will result in $myArray being sorted by age in ascending order.

Conclusion

This method provides a straightforward and efficient way to sort multi-dimensional arrays in PHP using the values of a specific key. By leveraging the array_column() function to extract the relevant values and then employing array_multisort(), developers can easily arrange array elements based on the desired criteria, maintaining the association between keys and values. This technique proves particularly useful when dealing with structured data, such as arrays of database records or configuration settings, where sorting by specific attributes is often necessary. Understanding and utilizing this approach empowers PHP developers to manipulate and organize complex data structures effectively.

References

  • array_multisort - Manual - PHP array_multisort - Manual - PHP | PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites in the world.
  • sorting - How to sort PHP multidimensional array by timestamp ... sorting - How to sort PHP multidimensional array by timestamp ... | Jun 22, 2013 ... In your example, we're just subtracting the first timestamp from the second to get this value (if the first item is greater, the result will be ...
  • How to Sort Multi-Dimensional Array by Key Value in PHP ... How to Sort Multi-Dimensional Array by Key Value in PHP ... | A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
  • sort multidimensional array by multiple fields - Programming ... sort multidimensional array by multiple fields - Programming ... | I’m creating an array by importing a CSV file using fgetcsv. Here is a short sample of the array: Array $arrCSV ( [0] => Array ( [Hearing_Sequence] => 39045780 [Start_Date_Time] => 6/21/2021 8:45:00 AM [Type] => Answer Hearing - Forcible Detainer [Case_Status] => Pending [Defendant_Name] => Hotel, Juliet ) [1] => Array ( [Hearing_Sequence] => 39021419 [Start_Date_Time] => 6/21/2...
  • How to sort a multi-dimension array by value in PHP - Virendra's ... How to sort a multi-dimension array by value in PHP - Virendra's ... | In this article we will see how to sort a multi-dimension array by value of one of the keys of the array. We can use a few different methods to do this.
  • How to Sort Multi-dimensional Array by Key Value in PHP ... How to Sort Multi-dimensional Array by Key Value in PHP ... | Sort multi-dimensional arrays by key - Use array_column() and array_multisort() function to sort multidimensional arrays by key in PHP. Example code snippet to order array by key value in PHP.
  • How do I count and sort simple multidimensional array like this? - PHP How do I count and sort simple multidimensional array like this? - PHP | Greetings, I have an array like this: Array ( [0] => Array ( [userid] => 1 [name] => Joe1 ) [1] => Array ( [userid] => 1 [name] => Joe1 ) [2] => Array ( [userid] => 2 [name] => Joe2 ) [3] => Array ( [userid] => 3 [name] => Joe3 ) [4] => Array ( [userid] => 2 [name] => Joe2 ) [5] => Array ( [userid] => 2 [name] => Joe2 ) ) The userid corresponds to a name. I would like to count up how many times the userid appears in the array. Then I would like to sort the array where the userid with ...
  • Mastering PHP's array_multisort() Function for Sorting ... Mastering PHP's array_multisort() Function for Sorting ... | Learn how to master the array_multisort() function in PHP for sorting multidimensional arrays with this comprehensive tutorial, including basic and advanced examples.
  • sorting multidimensional array by one value sorting multidimensional array by one value | Think of Laracasts sort of like Netflix, but for developers. You could spend weeks binging, and still not get through all the content we have to offer. Push ...

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait