За последние 24 часа нас посетили 22956 программистов и 1234 робота. Сейчас ищут 720 программистов ...

Список объектов в многомерный массив по заданным полям

Тема в разделе "Решения, алгоритмы", создана пользователем sphinks, 1 июл 2022.

  1. sphinks

    sphinks Активный пользователь

    С нами с:
    30 мар 2017
    Сообщения:
    7
    Симпатии:
    0
    Всем добра и счастья.
    Есть список объектов $objs класса Game.
    PHP:
    1. class Game{
    2.     public $id;
    3.     public $sport;
    4.     public $country;
    5.     public $league;
    6.  
    7.     public function __construct($id,$sport,$country,$league)
    8.     {
    9.         $this->id = $id;
    10.         $this->sport = $sport;
    11.         $this->country = $country;
    12.         $this->league = $league;
    13.     }
    14. }
    15. $objs = [
    16.     new Game(1,'Football','England','Premier League'),
    17.     new Game(4,'Football','England','Premier League'),
    18.     new Game(2,'Football','Europe',''),
    19.     new Game(3,'Tennis','England',''),
    20. ];
    21. $structure1=['sport','country','league'];
    22. $structure2=['country','sport','league'];
    Цель: задавая динамически структуру ($structure1, $structure2) получать структуру данных (многомерный массив) вида
    Код (Text):
    1. Array
    2. (
    3.     [Football] => Array
    4.         (
    5.             [England] => Array
    6.                 (
    7.                     [Premier League] => Array
    8.                         (
    9.                             [1] => Game Object
    10.                                 (
    11.                                     [id] => 1
    12.                                     [sport] => Football
    13.                                     [country] => England
    14.                                     [league] => Premier League
    15.                                 )
    16.  
    17.                             [4] => Game Object
    18.                                 (
    19.                                     [id] => 4
    20.                                     [sport] => Football
    21.                                     [country] => England
    22.                                     [league] => Premier League
    23.                                 )
    24.  
    25.                         )
    26.  
    27.                 )
    28.  
    29.             [Europe] => Array
    30.                 (
    31.                     [] => Array
    32.                         (
    33.                             [2] => Game Object
    34.                                 (
    35.                                     [id] => 2
    36.                                     [sport] => Football
    37.                                     [country] => Europe
    38.                                     [league] =>
    39.                                 )
    40.  
    41.                         )
    42.  
    43.                 )
    44.  
    45.         )
    46.  
    47.     [Tennis] => Array
    48.         (
    49.             [England] => Array
    50.                 (
    51.                     [] => Array
    52.                         (
    53.                             [3] => Game Object
    54.                                 (
    55.                                     [id] => 3
    56.                                     [sport] => Tennis
    57.                                     [country] => England
    58.                                     [league] =>
    59.                                 )
    60.  
    61.                         )
    62.  
    63.                 )
    64.  
    65.         )
    66.  
    67. )
    Пока делаю так:

    PHP:
    1. $graph=[];
    2. $graph2=[];
    3.  
    4. foreach($objs as $obj){
    5.     $graph[$obj->{$structure1[0]}][$obj->{$structure1[1]}][$obj->{$structure1[2]}][$obj->id]=$obj;
    6.     $graph2[$obj->{$structure2[0]}][$obj->{$structure2[1]}][$obj->{$structure2[2]}][$obj->id]=$obj;
    7. }
    но уверен, есть какое-то универсальное решение.
    Пока ковыряю интернет, но может кто уже решал такую задачу?
     
  2. sphinks

    sphinks Активный пользователь

    С нами с:
    30 мар 2017
    Сообщения:
    7
    Симпатии:
    0
    Нарыл и допилил такое решение.

    PHP:
    1. /**
    2. * @param array $items
    3. * @param string|array $key
    4. * @param bool $distinct
    5. * @return array
    6. */
    7. function group($items,$key,$distinct=true){
    8.         if(!is_array($key)) $key=[$key];
    9.  
    10.         $result=[];
    11.         foreach ($items as $item){
    12.             recursive_group($result,$key,$item,$distinct);
    13.         }
    14.         return $result;
    15.     }
    16.  
    17. function recursive_group(&$result, $keys, $obj, $distinct){
    18.         $key=array_shift($keys);
    19.         $index=$obj->$key;
    20.  
    21.         if(!isset($result[$index])) $result[$index]=[];
    22.         if(count($keys)) recursive_group($result[$index],$keys,$obj,$distinct);
    23.         else {
    24.             if($distinct)$result[$index]=$obj;
    25.             else $result[$index][]=$obj;
    26.         }
    27.     }
    Затык у меня был в рекурсии. А теперь все смотрится красиво.