0

I have array like this

Array
(
    [0] => Array
        (
            [id] => 16059
            [product_id] => 4013
            [Product] => Array
                (
                    [id] => 4013
                    [name] => XYZ
                )

        )

    [1] => Array
        (
            [id] => 16060
            [product_id] => 4462
            [Product] => Array
                (
                    [id] => 4462
                    [name] => MNOP
                )

        )

    [2] => Array
        (
            [id] => 16061
            [product_id] => 4473
            [Product] => Array
                (
                    [id] => 4473
                    [name] => ABCD
                )

        )
)

How to short this array using Product > name in ascending order. I can do using for-each loop, but there is any method to without loop ?

Yogesh Saroya
  • 1,401
  • 5
  • 23
  • 52

3 Answers3

3

Use usort() with strcmp():

usort($array, function($a, $b) {
   return strcmp($a['Product']['name'] , $b['Product']['name']);
});

print_r($array);

Output:- https://3v4l.org/Cb5S5

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
1

Try -

usort($array, function($a, $b) {
    return $a['Product']['name'] > $b['Product']['name'];
});

usort()

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
  • 4
    With case of strings it's better to use `strcmp` because with `>` your strings will be converted to ints, I presume. – u_mulder Jun 13 '19 at 07:31
  • Yes, they will be converted. But if they are only strings then it should word as it will compare in alphabetical order. – Sougata Bose Jun 13 '19 at 07:32
1

Here is the snippet,

$t = [];
foreach ($arr as $key => $value) {
    $t[$key] = $value['Product']['name'];
}
array_multisort($t, SORT_ASC, $arr);

First, fetch the data of that name and create an array.
Pass the relevant array for sorting criteria to a multidimensional array.

Demo.

Rahul
  • 18,271
  • 7
  • 41
  • 60