[英]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.