How to Naturally Sort Multidimensional Arrays with PHP

How to Naturally Sort Multidimensional Arrays with PHP

The sorting process is known as “natural ordering” or “multidimensional array natural sorting.”

  1. Natural Sorting of Multidimensional Array

    Sorting arrays with more than one dimension can be challenging for beginners. PHP can compare two text strings or two numbers. Still, in a multidimensional array, each element is an array.
    How to Sort Multidimensional Arrays with PHP

  2. PHP Procedure to Sort Multidimensional Array Naturally

    PHP does not know how to compare two arrays, especially if you wish to sort the array in a human-readable format while simultaneously maintaining the key/value pairs. You can sort the multidimensional array with the “natural order” algorithm.Sorting Multidimensional Arrays with PHP

Here’s a Multidimensional Array:

$data = [
  [
    'id' => 1794,
    'size' => 1,
    'color' => 'Red',
  ],
  [
    'id' => 1826,
    'size' => '2XL',
    'color' => 'Red',
  ],
  [
    'id' => 1827,
    'size' => 3,
    'color' => '',
  ],
  [
    'id' => 1825,
    'size' => 30,
    'color' => 'Black'
  ],
  [
    'id' => 1828,
    'size' => '3XL',
    'color' => 'Blue'
  ],
  [
    'id' => 1829,
    'size' => 'Medium',
'color' => 'Blue'
  ],
  [
    'id' => 1795,
    'size' => 'XS',
    'color' => 'Red'
  ]
];

The above array can be sorted in natural order by using the following code:

usort($data, function($a, $b) {
    return strnatcasecmp($a['size'], $b['size']);
});

//Print output
echo "<pre>";
print_r($aa);

strnatcasecmp() function used in the above code compares two strings using a “natural” algorithm. It returns the result based on input arguments, where the first argument specifies the first string to compare, and the second argument specifies the second string to compare.

Executing the above code will produce the following output:

Array
(
    [0] => Array
        (
            [id] => 1794
            [size] => 1
            [color] => Red
        )

    [1] => Array
        (
            [id] => 1826
            [size] => 2XL
            [color] => Red
        )

    [2] => Array
        (
            [id] => 1827
            [size] => 3
            [color] => 
        )

    [3] => Array
        (
            [id] => 1828
            [size] => 3XL
            [color] => Blue
        )

    [4] => Array
        (
            [id] => 1825
            [size] => 30
            [color] => Black
        )

    [5] => Array
        (
            [id] => 1829
            [size] => Medium
            [color] => Blue
        )

    [6] => Array
        (
            [id] => 1795
            [size] => XS
            [color] => Red
        )
)

Let’s create something beautiful and innovative together! call us now!

Chat with our seniors to see if we have a good match

SHARE IT ON

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

BLOG

Our recent post