我一直试图总结多个数组的值,但没有成功。我觉得我的大脑受不了了,因此我需要一些帮助或提示。
这是我到目前为止所取得的最好成绩:
$bani= array();
$iduri=array();
$total=0;
foreach($qp as $luna) {
$nsd_id=$luna['nsd_id']; // different ids every foreach
$nsd_amount=$luna['nsd_amount']; // different values every foreach
$nsd_id=explode("@",$nsd_id); // this makes them arrays
$nsd_amount=explode("@",$nsd_amount); // same , it makes them arrays
$iduri=array_merge($iduri,$nsd_id); // i tried getting making an array of all the ids it finds
for($x=0;$x<count($iduri);$x++){
$bani[$iduri[$x]] += intval($nsd_amount[$iduri[$x]]);
$total += intval($nsd_amount[$x]);
}
}
$iduri=array_unique($iduri,SORT_REGULAR);
print_r($iduri);
我尝试过将找到的每个ID组成一个数组,然后根据其位置将其求和到该数组中。
它确实可以累加一些东西,但是我没有得到正确的值,还有很多未定义的偏移量。
我觉得有比这简单的方法了,我真的很感谢一些建议。
谢谢! image of the columns in the DB i'm using
如果结果可能是以下内容的数组,我将不胜感激
Array (
[1] => 0
[2] => 2500
[3] => 62000
[4] => etc
[5] => etc
[12] => etc
[14] => etc )
(以id-s为键,将值的总和作为对应id的值)
qp的var_export
Mysqli_result::__set_state(Array( 'Current_field' => NULL, 'Field_count' => NULL, 'Lengths' => NULL, 'Num_rows' => NULL, 'Type' => NULL, ))
foreach(部分)内$ value的var_export
Array ( 'Id' => '329', 'Month' => 'May', 'Year' => '2019', 'Empid' => '124', 'Addedby' => 'PMSCLT10002', 'Nsd_id' => '1@2@3@4@5@12@14@15', 'Nsd_amount' => '0@0@0@0@0@0@4000@0', )
Array ( 'Id' => '303', 'Month' => 'April', 'Year' => '2019', 'Empid' => '124', 'Addedby' => 'PMSCLT10002', 'Nsd_id' => '1@2@3@4@5@12@14@15', 'Nsd_amount' => '0@0@2000@0@0@500@0@0', )
..等等
答案 0 :(得分:0)
这是您可以做的摘录,
$nsdIds = [];
$result = [];
foreach ($qp as $key => $value) {
// exploding Nsd_ids
$nsdTemp = explode("@", $value['Nsd_id']);
// exploding nsd_amounts
$nsdAmount = explode("@", $value['Nsd_amount']);
// saving all new nsd ids and only keep unique nsd ids
$nsdIds = array_unique(array_merge($nsdIds, $nsdTemp));
// I am now combining keeping nsd id as key and nsd amount as its value
$temp1 = array_combine($nsdTemp, $nsdAmount);
foreach ($nsdIds as $value1) {
// for latest php version
// $temp1 contains keys of nsd ids
// value1 contains nsdids we are sure that it will be in nsdids as we are already merging those ids
// then fetching amounf for that nsdids
//$result[$value1] = ($result[$value1] ?? 0) + $temp1[$value1];
// for php version less than 7
$result[$value1] = (!empty($result[$value1]) ? $result[$value1] : 0) +
(!empty($temp1[$value1]) ? $temp1[$value1] : 0);
}
}
print_r($result);die;
答案 1 :(得分:0)
只要同一行中的nsd_id
和nsd_amount
在@
之间具有相同数量的值,那么它应该起作用。如果不是,那么您需要isset
来检查$nsd_amount[$key]
:
foreach($qp as $luna) {
$nsd_id = explode("@", $luna['nsd_id']);
$nsd_amount = explode("@", $luna['nsd_amount']);
foreach($nsd_id as $key => $id) {
if(isset($result[$id])) {
$result[$id] += $nsd_amount[$key];
} else {
$result[$id] = $nsd_amount[$key];
}
}
}