Simon Simon - 5 months ago 12
PHP Question

PHP How to restructure an array?

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
)
))


Thanks.

Edit:

This is what I needed. Thanks for the answers.

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

Answer

Try this:

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

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

Comments