-2

I fetched the information from the table and get the following array. The number of array items may change and dynamic. The array obtained:

Array
(
  [0] => Array
    (
      [category_id] => 1178
      [parent_id] => 889
    )

  [1] => Array
    (
      [category_id] => 1179
      [parent_id] => 889
    )

  [2] => Array
    (
      [category_id] => 1180
      [parent_id] => 890
    )
)

In this array, the key ("parent_id") also changes dynamically.

I would like to change the array with the key ("parent_id"). For example as follows:

Array
(
  [889] => Array
    (
      [0] => Array
        (
          [category_id] => 1178
        )
      [1] => Array
        (
          [category_id] => 1179
        )
    )

  [890] => Array
    (
      [0] => Array
        (
          [category_id] => 1180
        )
    )
)
Masoud Tesna
  • 47
  • 2
  • 9
  • 1
    There have been numerous questions about restructuring arrays in one way or another. A rather simple loop can take care of this. Have you tried anything? While we're glad to help if you're stuck, you are still expected to make an effort of your own. – El_Vanja Mar 17 '21 at 17:08
  • Does this answer your question? [How to group subarrays by a column value?](https://stackoverflow.com/questions/12706359/how-to-group-subarrays-by-a-column-value) – El_Vanja Mar 17 '21 at 17:10

1 Answers1

0

Simple Loop with key as parent_id

$arr = [
    [
        'category_id' => 1178,
        'parent_id' => 889
    ],[
        'category_id' => 11,
        'parent_id' => 889
    ],[
        'category_id' => 117,
        'parent_id' => 88
    ],[
        'category_id' => 1178,
        'parent_id' => 88
    ],[
        'category_id' => 117,
        'parent_id' => 89
    ],
];


$res = [];

foreach($arr as $val){
    
    $parent_id = $val['parent_id'];
    $res[$parent_id][] = ['category_id'=> $val['category_id'] ];
}

print_r($res);

Result:

Array
(
    [889] => Array
        (
            [0] => Array
                (
                    [category_id] => 1178
                )

            [1] => Array
                (
                    [category_id] => 11
                )

        )

    [88] => Array
        (
            [0] => Array
                (
                    [category_id] => 117
                )

            [1] => Array
                (
                    [category_id] => 1178
                )

        )

    [89] => Array
        (
            [0] => Array
                (
                    [category_id] => 117
                )

        )

)
Umer Abbas
  • 1,866
  • 3
  • 13
  • 19