我从数据库中获取数据。我有两个表是关系表。我正在使用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);
}
我想通过所有数组并整齐地回应它们并按照图片中的顺序排序。
答案 0 :(得分:1)
如果输出就像这个数组(你可以设置你需要的键)
$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>';
}