簡體   English   中英

PHP如何重組數組?

[英]PHP How to restructure an array?

我有一個要重組的數組。 我想按順序對項目進行分組。 我可以弄清楚如何使用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'];
  }
}

嘗試這個:

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

擺弄吧! http://ideone.com/BtKOKJ

您可以開始將數據添加到新陣列。 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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM