PHP如何重组数组?

时间:2016-06-06 22:10:02

标签: php arrays

我有一个我想重组的阵列。我想轮流分组。我可以弄清楚如何使用foreach($arr['history'] as $obj)从数组中提取数据我的问题是使用循环填充新数组。

目前它看起来像这样:

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

我希望它看起来如下,但我无法弄清楚如何自动创建和填充此结构。这是一个数组,每个回合都有一个子数组,包含一个数组给我和对手

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

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

感谢。

修改

这就是我需要的。谢谢你的回答。

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

2 个答案:

答案 0 :(得分:2)

试试这个:

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

小提琴! http://ideone.com/BtKOKJ

答案 1 :(得分:1)

您可以开始向新阵列添加数据。 PHP非常宽容。

$historyByTurns = array();
foreach ($arr['history'] as $historyItem) {
    foreach ($historyItem['legend'] as $legendItem) {
        $turn = $legendItem['turn'];
        $player = $legendItem['player'];
        if (!array_key_exists($turn, $historyByTurns)) {
            $historyByTurns[$turn] = array();
        }
        if (!array_key_exists($player, $historyByTurns[$turn])) {
            $historyByTurns[$turn][$player] = array();
        }
        foreach ($legendItem as $card) {
            $historyByTurns[$turn][$player][] = $card['name'];
        }
    }
}

你必须测试它,因为我无法使用那台ATM。