S
S
siroper2019-08-05 15:44:05
PHP
siroper, 2019-08-05 15:44:05

How to sort an array - stdclass by key value?

Hello. There is an array $variants
print_r array:

Array
(
    [0] => stdClass Object
        (
            [id] => 84
            [product_id] => 48
            [price] => 277.00
            [compare_price] => 300.00
            [name] => Яблочный
        )

    [1] => stdClass Object
        (
            [id] => 58
            [product_id] => 43
            [price] => 277.00
            [compare_price] => 1233.00
            [name] => Черный
        )

    [2] => stdClass Object
        (
            [id] => 85
            [product_id] => 48
            [price] => 277.00
            [compare_price] => 413.00
            [name] => Малахитовый
        )
)

Can you please tell me how to sort an array by [name], preserving the structure?
Tried
function cmp_function($a, $b){
  return ($a['name'] > $b['name']);
}
uasort($variants, 'cmp_function');

Produces respectively Fatal error: Cannot use object of type stdClass as array here stdClass

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikolay, 2019-08-05
@siroper

function cmp_function($a, $b) {
  return ($a->name > $b->name);
}
uasort($variants, 'cmp_function');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question