簡體   English   中英

合並具有相同ID的數組

[英]Combine arrays with the same id

我正在從數據庫中獲取數據。 我有兩個表是關系表。 我正在使用sql JOIN來獲取所需的信息。 現在我有多個數組,其中有數據。 但是現在我想將具有相同ID(team_id)的數組組合在一起,然后在頁面上回顯它。 或者我的意思是將具有相同ID(team_id)的陣列組合在一起,我可以為每個團隊正確地對其進行排序。

這是來自數據庫的數組。 團隊名稱(數組)可以是無數個。

Array
(
    [points_1] => 2
    [0] => 2
    [points_2] => 10
    [1] => 10
    [name] => Team 1
    [2] => Team 1
    [team_id] => 1
    [3] => 1
)
Array
(
    [points_1] => 7
    [0] => 7
    [points_2] => 10
    [1] => 10
    [name] => Team 1
    [2] => Team 1
    [team_id] => 1
    [3] => 1
)
Array
(
    [points_1] => 10
    [0] => 10
    [points_2] => 10
    [1] => 10
    [name] => Team 1
    [2] => Team 1
    [team_id] => 1
    [3] => 1
)
Array
(
    [points_1] => 4
    [0] => 4
    [points_2] => 15
    [1] => 15
    [name] => Team 1
    [2] => Team 1
    [team_id] => 1
    [3] => 1
)
Array
(
    [points_1] => 14
    [0] => 14
    [points_2] => 14
    [1] => 14
    [name] => Team 1
    [2] => Team 1
    [team_id] => 1
    [3] => 1
)
Array
(
    [points_1] => 22
    [0] => 22
    [points_2] => 22
    [1] => 22
    [name] => Team 1
    [2] => Team 1
    [team_id] => 1
    [3] => 1
)
Array
(
    [points_1] => 1
    [0] => 1
    [points_2] => 10
    [1] => 10
    [name] => Team 2
    [2] => Team 2
    [team_id] => 3
    [3] => 3
)
Array
(
    [points_1] => 10
    [0] => 10
    [points_2] => 10
    [1] => 10
    [name] => Team 3
    [2] => Team 3
    [team_id] => 6
    [3] => 6
)

這是我的Foreach / JOIN代碼:

echo "<pre>";
    foreach ($db->query("SELECT points_1, points_2, name, team_id FROM points INNER JOIN teams ON teams.id=points.team_id ORDER BY team_id ASC") as $result) {
        print_r($result);

    }

我想遍歷所有數組並整齊地回顯它們,並按圖片中的順序進行排序。

在此處輸入圖片說明

如果您的輸出類似於此數組(可以設置所需的鍵)

$arr = array(
array('name' => 'Team 1','points_1' => 2,'points_2' => 10),
array('name' => 'Team 1','points_1' => 7,'points_2' => 10),
array('name' => 'Team 2','points_1' => 1,'points_2' => 12),
array('name' => 'Team 3','points_1' => 4,'points_2' => 32),
array('name' => 'Team 2','points_1' => 1,'points_2' => 16),
);

然后嘗試:

$arrayTotals = array();


foreach ($arr as $result) {
        //print_r($result);

        $arrayTotals[$result['name']][] = array('points_1'=>$result['points_1'],'points_2'=>$result['points_2']);

}

var_dump($arrayTotals);

foreach($arrayTotals as $team=>$values){
    echo '<div style="float:left;">'.$team;
    $sum1=0;
    $sum2=0;
    foreach($values as $v){
        echo '<br />'.$v['points_1'].'/'.$v['points_2'];
        $sum1 +=$v['points_1'];
        $sum2 +=$v['points_2'];
    }
    echo '<br />Total:'.$sum1.'/'.$sum2;
    echo '</div>';
}

暫無
暫無

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

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