There was a task to sort an array coming from a DB. One element from this array looks like this:

Array ( [id] => 261 [category] => 1 [subcategory] => 83 [name] => Гель-краска 10 г цвет 02 [name_tr] => [description] =>[description_tr] =>[price-usd] => [price-usd-promo] => [price-try] => [price-try-promo] => [price-rub] => [price-rub-promo] => [image] => 02в.jpg [sku] => [status] => 1 [novelty] => [recommended] => [promo] => [sales] => [hits] => [type] => 2 [volume] => [width] => [height] => [thickness] => [weight] => [material] => [abrasiveness] => [seo_title] => [seo_description] => [seo_keywords] => ) 

It is necessary to sort this array by the name field in ascending order. Names for one category do not change, but change for another. At the end there is always a number of the form

01, 02, 021

You can sort by SQL query

$sql ="SELECT * FROM c_products WHERE category = '".$category[0]['id']."' AND status = '1' AND subcategory = '".$subcategory[0]['id']."' ORDER BY name ASC LIMIT $offset,$num ";

With existing sorting is displayed as follows

01, 011, 012, 02, 020

  • So you need to sort by this last number in the name without considering everything else? - n.osennij
  • Yes, despite the fact that the names change, and the length of the number can consist of 2 or 3 digits. - Andrei Sulyz
  • one
    the most correct thing is to store this data in a database in a separate column. Like grams. And all the dances with a tambourine will be gone. What you have now is not a name. This is the name and characteristics of the product (weight and color). They must be separate. - n.osennij
  • I completely agree, but the site was given for revision and the goods have already been filled in, therefore, it’s more difficult to redo it than to finish sorting - Andrey Sulyz

3 answers 3

To sort the data in php, you can use the usort function

 $data = [ ['id' => 1, 'name' => 'Name qweqweqwe 17'], ['id' => 3, 'name' => 'Name qweqweqwe 09'], ['id' => 4, 'name' => 'Name qweqweqwe 2'], ['id' => 5, 'name' => 'Name qweqweqwe 15'], ['id' => 7, 'name' => 'Name qweqweqwe 021'], ['id' => 9, 'name' => 'Name qweqweqwe 8'], ]; usort($data, function($a, $b){ $a = explode(' ', $a['name']); $b = explode(' ', $b['name']); return array_pop($a) - array_pop($b); }); print_r($data); 

3v4l.org

  • Thanks It works! - Andrey Sulyz

The data structure needs to be changed. I will offer a plan for a painless transition.

Data migration

  • Get new columns for meaningful data ( title , weight , color )
  • Write a script that parses the name and fills in the new fields.

Maintaining consistency

To maintain the consistency of the data during operation, you need to change all the code that works with this data.

Therefore, for this time I suggest adding a trigger to the database, which parses the name into parts when inserting or updating.
In many frameworks, you can also place a call to a previously written function in the ORM hooks.

  • Thanks for the advice, I will try - Andrei Sulyz

I suggest this: get an array in which you will put all the data obtained from the database and an array for the color code. All the obtained data are sorted and the name is cut into pieces. Because at the end there is always the number we need to sort, then we get it and put it in the second array for the color code, and all the data in the first array. Then we sort our new array with the help of another array and work with it. Something like this (just for one name here):

 $global_array=[]; //Глобальный массив в который помщаем все данных из запроса и цвет отдельной переменной $sorting_values=[]; //значния для сортировки - код цвета $name='Гель-краска 10 г цвет 02'; $name_arr=explode(' ', $name); //режем name на части по пробелу $сolor=array_pop($name_arr); //получаем последнюю часть массива с кусками name, т.е. код цвета $global_array[]=$name; //заносим нужные данные в глобальный массив (все переменные из запроса). НО ключи - цифры по порядку! Вам тут скорее всего нужно будет завести многомерный массив $sorting_values[]=$сolor; //код цвета в отдельный массив. Ключи тоже цифры по порядку. Они должны совпадать с указанными в $global_array array_multisort($sorting_values, $global_array); //сортируем массив global_array по sorting_values print_r($global_array);