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 ?

6
  • 1
    "without loop" not really, because also the native functions (usort) loop under the hood. usort would be one way to go btw. Commented Jun 13, 2019 at 7:27
  • @Jonnix that have different array Commented Jun 13, 2019 at 7:28
  • @YogeshSaroya So? The principle is still the same. Commented Jun 13, 2019 at 7:30
  • 1
    “that have different array” - so what? Then adapt it accordingly, after you made the effort to understand how this works in principle … Commented Jun 13, 2019 at 7:30
  • 1
    array_multisort(array_column(array_column($arr, 'Product'),'name'), SORT_ASC, $arr); Commented Jun 13, 2019 at 7:41

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

2

Try -

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

usort()

2 Comments

With case of strings it's better to use strcmp because with > your strings will be converted to ints, I presume.
Yes, they will be converted. But if they are only strings then it should word as it will compare in alphabetical order.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.