hello every one i have small issue are there in mysqli and php
i have a table with multiple rows and i will pickup for one column values in an array sum of these values based on rows.
here i will place the image like this array[0] + array[0] + array[0] = some value
and array [n] + array[n] +array [n] = some of value can print how
my code is
<?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;
}
}
}
?>
my database is look like this
Given an array of comma separated values, this is how you calculate the sum of each quasi-column individually.
$pur_amount = [
"6250,2500,26000,12500,9000",
"6250,2500,26000,12500,9000",
"6250,2500,26000,12500,9000",
"6250,2500,26000,12500,9000",
];
$pur_sum = [];
foreach($pur_amount as $string){
foreach(explode(",", $string) as $id => $val){
if(!array_key_exists($id, $pur_sum)){
$pur_sum[$id] = 0;
}
$pur_sum[$id] += $val;
}
}
var_dump($pur_sum);
MySQL queries can be a good choice but you can try this as a PHP solution.
$arr = [
[5,5,5,3,1],
[6,4,2,3,5],
[4,3,42,6,3]
];
var_dump(array_sum(array_column($arr, 0)));
var_dump(array_sum(array_column($arr, 1)));
var_dump(array_sum(array_column($arr, 2)));
var_dump(array_sum(array_column($arr, 3)));
var_dump(array_sum(array_column($arr, 4)));
int(15) int(12) int(49) int(12) int(9)