【发布时间】:2019-07-19 23:30:35
【问题描述】:
大家好,我遇到的小问题都在 mysqli 和 php 中
我有一个包含多行的表,我将根据行在这些值的数组总和中提取一列值。
在这里我将像这样放置图像 array[0] + array[0] + array[0] = some value
and array[n] + array[n] +array [n] = some of value 可以打印如何
我的代码是
<?php
$sql2="SELECT * FROM `purchase_data` where `project_id` ='$proid'";
$result2 = $conn->query($sql2);
$count2=$result2->num_rows;
if ($count2 > 0) {
$x=1;
$tot = 0;
while ($pur_row = $result2->fetch_assoc()) {
//$proid =$pur_row['pur_id'];
$category = $pur_row['pur_category'];
$categories = explode(',',$category);
$lenght = count($categories);
//var_dump($category);
$est_amou = $pur_row['pur_amount'];
$est_amount = explode(',',$est_amou);
var_dump($est_amount);
//echo $ans_count = array_sum($est_amount);
//echo $value = array_sum(array_column($est_amount,'pur_amount'));
$sum = array();
foreach ($categories as $key => $sub_array) {
echo $sub_array;
foreach ($est_amount as $sub_key => $value) {
echo $value;
//If array key doesn't exists then create and initize first before we add a value.
//Without this we will have an Undefined index error.
if( ! array_key_exists($sub_key, $sum))
$sum[$sub_key] = 0;
//Add Value
$sum[$sub_key]+=$value;
}
}
print_r($sum);
for($i=0; $i< $lenght; $i++)
{
$x++;
$tot = $tot + $est_amount[$i];
// $balance = $estimation - $tot;
}
}
}
?>
我的数据库是这样的
【问题讨论】:
-
请探索
array_sum()和array_map() -
您是否考虑过在 SQL 中进行求和?
-
@dearsina:嗯,好主意。
-
你应该从规范化你的数据库开始,如果你想操作数据,在你的数据库中存储逗号分隔的值是一个坏主意。然后您可以使用
SUM和GROUP BY在sql 中进行数学运算。
标签: php arrays mysqli multidimensional-array