TransWikia.com

Помогите отсортировать массив php

Stack Overflow на русском Asked on January 26, 2021

Помогите пожалуйста с сортировкой. Есть примерно такой массив:

[1]=>
  array(12) {
    ["TEXT"]=>
    string(20) "Полиграфия"
    ["LINK"]=>
    string(22) "/services/poligrafiya/"
    ["CHILDREN"]=>
    array(3) {
      [2]=>
      array(11) {
        ["TEXT"]=>
        string(12) "Газеты"
        ["LINK"]=>
        string(29) "/services/poligrafiya/gazety/"
        ["PARAMS"]=>
        array(4) {
          ["DEPTH_LEVEL"]=>
          int(2)
          ["USORT"]=>
          string(3) "650"
        }
      }
      [3]=>
      array(11) {
        ["TEXT"]=>
        string(12) "Журналы"
        ["LINK"]=>
        string(29) "/services/poligrafiya/jurnal/"
        ["PARAMS"]=>
        array(4) {
          ["DEPTH_LEVEL"]=>
          int(2)
          ["USORT"]=>
          string(3) "620"
        }
      }
[4]=>
      array(11) {
        ["TEXT"]=>
        string(12) "Книги"
        ["LINK"]=>
        string(29) "/services/poligrafiya/book/"
        ["PARAMS"]=>
        array(4) {
          ["DEPTH_LEVEL"]=>
          int(2)
          ["USORT"]=>
          string(3) "690"
        }
      }

Задача – отсортировать все элементы ветки ["CHILDREN"] по полю ["PARAMS"]["USORT"] по возрастанию.
Пытаюсь сделать так:

foreach ($aMenuLinksNew as $key => $value)
        {
         
          if(!empty($value["CHILDREN"])) 
           {
               usort($value["CHILDREN"][$key], function($a, $b) {
               if ($a["PARAMS"][USORT] == $b["PARAMS"]["USORT"])
                  return 0;
               return ($a["PARAMS"][USORT] < $b["PARAMS"]["USORT"]) ? -1 : 1;
}
);
               
           }
            
        };

Подскажите, что делаю не так?

One Answer

$data = [
    ['CHILDREN' => ['PARAMS' => [
        ['USORT' => 9, 'TITLE' => 'NINE'],
        ['USORT' => 8, 'TITLE' => 'EIGHT'],
        ['USORT' => 7, 'TITLE' => 'SEVEN'],
    ]]],
    ['CHILDREN' => ['PARAMS' => [
        ['USORT' => 9, 'TITLE' => 'NINE'],
        ['USORT' => 7, 'TITLE' => 'SEVEN'],
    ]]],
];

foreach ($data as &$row) {
    usort($row['CHILDREN']['PARAMS'], static function($a, $b) {
        return $a['USORT'] <=> $b['USORT'];
    });
}
unset($row);

echo json_encode($data);

Answered by vp_arth on January 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP