Search code examples
phparraysmultidimensional-arraygrouping

Consolidate multidimensional array data by deep array value and ensure default-keyed subarrays within each group


I have an array that I'd like to restructure. I want to group items by turn. I can figure out how to extract data from the array using foreach($arr['history'] as $obj) my issue is with populating a new array using a loop.

Currently it looks like this:

Array ( 
[history] => Array ( 
    [id] => 23452435 
    [legend] => Array ( 

        [0] => Array ( 
            [player] => me 
            [turn] => 1 
            [card] => Array ( 
                [name] => foo 
            ) 
        ) 

        [1] => Array ( 
            [player] => me 
            [turn] => 1 
            [card] => Array ( 
                [name] => bar
            ) 
        ) 

        [2] => Array ( 
            [player] => opponent 
            [turn] => 1
            [card] => Array (
                [name] => derp 
            ) 
        ) 

        [3] => Array ( 
            [player] => opponent 
            [turn] => 2 
            [card] => Array ( 
                [name] => hoo
            ) 
        ) 
    ) 
))

I want it to look like the following, but I can't figure out how to automatically create and populate this structure. This is an array with a sub-array for each turn, containing an array for me and opponent

Array (
[0] => Array (
    [me] => Array (
        [0] => foo
        [1] => bar
    )
    [opponent] = Array (
        [0] => derp
    )

)
[1] => Array (
    [me] => Array ()
    [opponent] => Array (
        [0] => hoo
    )
))

Solution

  • Try this script which subtracts 1 from the turn value to declare the first level key and then the player value as the second level key, then pushes the card value as a new subarray element.

    $result = [];
    foreach ($data['history']['legend'] as $list) {
        $result[$list['turn'] - 1][$list['player']][] = $list['card']['name'];
    }
    

    Fiddle it! http://ideone.com/BtKOKJ