[英]MySQL PHP fill out an empty array
I have a database in which the size of each service used is being saved. 我有一个数据库,其中保存了所使用的每个服务的大小。 In my table the first column is for name_service
, the second for size
. 在我的表中,第一列是name_service
,第二列是size
。 So what i need to do is to put the total size of each service, knowing that lines with the same service name may be repeated! 因此,我需要做的是放入每个服务的总大小,因为知道具有相同服务名称的行可能会重复!
$serviceCounts=array();
while ($row=mysqli_fetch_assoc($result))
{
$size=$row['size'];
$service=$row['name_service'];
}
SQL Solution Check out @Adder solution. SQL解决方案签出@Adder解决方案。
PHP Solution PHP解决方案
Before the loop: 循环之前:
$services = array();
Inside the loop: 循环内:
if(array_key_exists($row['name_service'] , $services))
{
$services[$row['name_service'] += $row['size'];
}
else
{
$services[$row['name_service'] = $row['size'];
}
You're basically using a new array named services
and checking in the loop if this service already set in the array or not. 基本上,您正在使用一个名为services
的新数组,并在循环中检查该服务是否已在数组中设置。 In case that yes - add to it the new row's size, otherwise add the service name as a new element and set its size. 在情况下是 - 给它添加新行的大小,否则添加服务名称作为新元素,并设置其大小。
Use the aggregation mysql functionality: 使用聚合mysql功能:
SELECT sum(size) as size, name_service FROM services GROUP BY name_service;
Untested, you might have to rename the sum(size) as sum_size
. 未经测试,您可能必须将sum(size) as sum_size
重命名sum(size) as sum_size
。
$serviceCounts=array();
while ( $row = mysqli_fetch_assoc($result) )
{
$size=$row['size'];
$service=$row['name_service'];
if (isset($serviceCounts[ $service ])) {
$serviceCounts[$service] += $size;
} else {
$serviceCounts[$service] = $size;
}
}
Then you can do this to print out the service name and size: 然后,您可以执行以下操作以打印出服务名称和大小:
foreach ($serviceCounts as $name=>$size) {
echo "$name: $size\n";
}
Do You mean something like that? 你的意思是那样吗?
$serviceCounts=array();
while ($row=mysqli_fetch_assoc($result) {
$size=$row['size'];
$service=$row['name_service'];
if (isset($serviceCounts[$service])) {
$serviceCounts[$service]+=$size;
} else {
$serviceCounts[$service]=$size;
}
}
print_r($serviceCounts);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.