Search code examples
phparrays

Push rows of a 2d array as children of the first encountered row with a given column value


I have a list of items stored in a DB and after requesting them, they are in an array ($data). Now there are about 200 items in the array and each of them itself is a key value array. Each element in the data array has a key called [Acr] and a name assigned to it.

Now the problem is that in this array

Array
( 
    [0] => Array
        (
            [ID] => 2
            [Name] => Name Here
            [Acr] => ARR
            [Valid] => 1
            [Orig] => 1
        )

    [1] => Array
        (
            [ID] => 2
            [Name] => Name Here
            [Acr] => ABC
            [Valid] => 1
            [Orig] => 1
        )

    [2] => Array
        (
            [ID] => 2
            [Name] => Name Here
            [Acr] => XYZ
            [Valid] => 1
            [Orig] => 1
        )
    ...
 

There are items that have the same Acr but are sub elements of the first item with that Acr. So for example there are 10 more items in $data that have the Acr as ARR and I want to add those sub elements into the original (aka the first) array item with that Acr value under the key called sub. So after iterating it makes this.

Array
( 
    [0] => Array
        (
            [ID] => 2
            [Name] => Name Here
            [Acr] => ABC
            [Valid] => 1
            [Orig] => 1
        )

     .....

    [14] => Array
        (
            [ID] => 2
            [Name] => Name Here
            [Acr] => ARR
            [Valid] => 1
            [Orig] => 1
            [Sub] =>
                    [0] => Array
                        (
                            [ID] => 23
                            [Name] => Sub Name Here
                            [Acr] => ARR
                            [Valid] => 1
                            [Orig] => 0
                        )

                    [1] => Array
                        (
                            [ID] => 24
                            [Name] => Sub Name Here
                            [Acr] => ARR
                            [Valid] => 0
                            [Orig] => 1
                        )
        )

       ...

Now I'm not sure how to do this. Also, its all sorted so when you see the first ARR all the sub ARR are right under them and there are only about 5 original categories that have sub elements so if there's a way that can do this by knowing which ones to append, that would be great.


Solution

  • For the case, that alpha-numeric keys are accepted in manipulated array:

    $new = array();
    foreach ($array as $entry) {
      if (!array_key_exists($entry['Acr'], $new)) {
        $entry['Sub'] = array();
        $new[$entry['Acr']] = $entry;
      } else $new[$entry['Acr']]['Sub'][] = $entry;
    }