M
M
m4f12019-12-07 11:07:23
PHP
m4f1, 2019-12-07 11:07:23

How to sort objects (alphabetical order) in a query by value?

There is a multidimensional array where you need to sort the values ​​alphabetically.
The array was uploaded to pastebin, it does not fit here.
shopColorValue object should be alphabetized by field value shopColorValuevalue => 'color'
I was able to reduce a multidimensional array into a normal one:

foreach ( $filters as $filter ) {
            //arsort($filter);
            foreach ( $filter as $key => $value ) {
                wa_dump($filter);
            }
        }

Outputs:
Array
(
  id => '675'
  parent_id => NULL
  code => 'tsvet1'
  status => 'public'
  name => 'Цвет'
  type => 'color'
  selectable => '1'
  multiple => '1'
  count => '25'
  values => Array
  (
    27 => shopColorValue object
    {
      shopColorValuecode => '0'
      shopColorValuevalue => 'чёрный'
      shopColorValueid => '27'
      shopColorValuesort => '1'
      shopColorValue_data => NULL
      feature_id => '675'
    }
    34 => shopColorValue object
    {
      shopColorValuecode => '255'
      shopColorValuevalue => 'синий'
      shopColorValueid => '34'
      shopColorValuesort => '9'
      shopColorValue_data => NULL
      feature_id => '675'
    }
    )
  )

How to now sort objects by given values ​​and return everything back to the
$filters
UPD
variable Now the code looks like this:
public function sortirovka_filters($filters) {

function cmp_obj($a, $b):bool {
    $al = strtolower($a->shopColorValuevalue);
    $bl = strtolower($b->shopColorValuevalue);
    if ($al == $bl) {
return 0;
    }
    return ($al > $bl) ? +1 : -1;
}

uasort($filters['675']['values'], "cmp_obj");

return $filters;
}

The dump gives this https://pastebin.com/XbQyaZ3B

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Araik, 2019-12-07
@m4f1

usort
php - sorting an array of objects by object fields
Sorting objects in PHP 7
Sorting objects in PHP
An example for your data:

usort($array['675']['values'], function($a, $b)  {
            return $a->color <=> $b->color;
        });

Key-preserving:
uasort
uasort($array['675']['values'], function($a, $b)  {
            return $a->color <=> $b->color;
        });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question