-1

I have set of arrays which need to be sort array by ascending and descending order in php?

Array
(
    [0] => Array
        (
            [product_name] => Blips
            [product_url] => 
            [product_id] => 123
            [state] => GA

        )

    [1] => Array
        (
            [product_name] => Alpha               
            [product_id] => 586
            [state] => GA
            )
)
nick
  • 1
  • 3
    How can you sort by "ascending and descending" at the same time? Is this array being built from a SQL query? If so using `order by` is probably a better approach, but you're going to need to clarify your ordering requirements. – user3783243 Jul 04 '18 at 10:50
  • 1
    Possible duplicate of [How can I sort arrays and data in PHP?](https://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – Adrian W Jul 04 '18 at 10:59

1 Answers1

0

You can use usort and strnatcmp to achieve that:

usort($myArray, function($a, $b) {
    return strnatcmp($a['product_name'], $b['product_name']);
});

If you want it sorted in descending order then you simply reverse the array after sorting it:

$myArray = array_reverse($myArray);
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50