-1

Given a multi dimensional array like:

[{"nomeCategoria":"Edilizia","costoCategoria":"350000"},
{"nomeCategoria":"Ingegneria","costoCategoria":"234000"},
{"nomeCategoria":"Ingegneria","costoCategoria":"275000"},
{"nomeCategoria":"Edilizia","costoCategoria":"328000"}]

How would I end up with the total sum for Edilizia and Ingegneria?

I'm not sure how to approach the foreach, there could be plenty of different objects and I am getting confused with the index, they will always be a pair values.

This is how I am pushing in a loop:

$costiCategorie[] = array("nomeCategoria"=>$singleCat["nome_categoria"], "costoCategoria"=>$singleCat["costo"]);

And then

$totCostiEdilizia = array();
foreach ($costiCategorie as $singleCostiCategorie) {
    array_push($totCostiEdilizia, $singleCostiCategorie["costoCategoria"]);
}
                $importo = array_sum($totCostiEdilizia);
                $importo = money_format('%.2n', $importo);
                echo "Costi totali Edilizia = " .$importo;
rob.m
  • 9,843
  • 19
  • 73
  • 162

4 Answers4

3

Just loop through all of your categories, and add the category name as a key to a new array, then increment the value for that name.

//original array
$costiCategorie = [
    ['nomeCategoria' => 'Edilizia', 'costoCategoria' => 350000],
    ['nomeCategoria' => 'Ingegneria', 'costoCategoria' => 234000],
    ['nomeCategoria' => 'Ingegneria', 'costoCategoria' => 275000],
    ['nomeCategoria' => 'Edilizia', 'costoCategoria' => 328000]
];

//array to hold totals
$totals = array();

//loop through categories
foreach($costiCategorie as $category) {

    $name = $category['nomeCategoria'];
    $cost = $category['costoCategoria'];

    //create `$name` key in `$totals` array if it doesn't already exist
    if(empty($totals[$name])) {
        $totals[$name] = 0;
    }

    //increment total for `$name` in `$totals` array
    $totals[$name] += $cost;

}

print_r($totals);

Output:

Array ( [Edilizia] => 678000 [Ingegneria] => 509000 )

Now you have an array with each category name as a key, and a total cost for each category.

You can get the total for either name by doing, for example, $totals['Edilizia'].

GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71
  • I tried then `foreach($totals as $total) { echo $total[$name].' total costs= '.$total[$cos]; }` as i wanted the single results with the names but nothing – rob.m Jul 15 '19 at 18:32
  • @rob.m I'm sorry, I don't quite understand your comment. If you just want to list the totals for each one, do `foreach($totals as $name => $total) { echo "{$name} total costs={$total}"; }` – GrumpyCrouton Jul 15 '19 at 19:48
  • yup got it, now just one last thing if I might, how would you echo the sum of both costs? – rob.m Jul 15 '19 at 19:54
  • 1
    @rob.m You could easily just do `array_sum($totals)`. Will work no matter how many unique category names there are. – GrumpyCrouton Jul 15 '19 at 19:55
  • superb, thanks a lot – rob.m Jul 15 '19 at 20:55
1

You're missing a check for the right category if I understand your code correctly:

<?php 

$array = [
  [
    "nomeCategoria" =>"Edi",
    "costoCategoria" => "350000"
  ],
  [
    "nomeCategoria" =>"Inge",
    "costoCategoria" => "350000"
  ],
  [
    "nomeCategoria" =>"Edi",
    "costoCategoria" => "350000"
  ],
  [
    "nomeCategoria" =>"Inge",
    "costoCategoria" => "350000"
  ]
];

$totalEdi = [];
foreach($array as $item){
  if($item["nomeCategoria"] === "Edi"){
    array_push($totalEdi, $item["costoCategoria"]);
  }
}

echo array_sum($totalEdi);

Updated for dynamic names:

<?php 

$array = [
  [
    "nomeCategoria" =>"Edi",
    "costoCategoria" => "350000"
  ],
  [
    "nomeCategoria" =>"Inge",
    "costoCategoria" => "350000"
  ],
  [
    "nomeCategoria" =>"Edi",
    "costoCategoria" => "350000"
  ],
  [
    "nomeCategoria" =>"Inge",
    "costoCategoria" => "350000"
  ]
];

$totals = [];

foreach($array as $item){
  if(isset($totals[$item["nomeCategoria"]])){
    $totals[$item["nomeCategoria"]] += $item["costoCategoria"];
  } else {
    $totals[$item["nomeCategoria"]] = $item["costoCategoria"];
  }
}

print_r($totals);
0

Add the values to own subarrays and sum them respectively.

$totCostiEdilizia = array();
foreach ($costiCategorie as $singleCostiCategorie) {
    $totCostiEdilizia[$singleCostiCategorie["nomeCategoria"]][] =$singleCostiCategorie["costoCategoria"];
}
var_dump($totCostiEdilizia);
echo "Costi totali Edilizia = " . array_sum($totCostiEdilizia["Edilizia"]) . "\n";

echo "Costi totali Ingegneria = " . array_sum($totCostiEdilizia["Ingegneria"]) . "\n";

https://3v4l.org/gKmNq

Andreas
  • 23,610
  • 6
  • 30
  • 62
-1

assuming you need the json format, i would use code like this

<?php

// first i parse the json to array (make sure set true in second parameter which may cause json parsed onto object
$data = json_decode("[{"nomeCategoria":"Edilizia","costoCategoria":"350000"},
{"nomeCategoria":"Ingegneria","costoCategoria":"234000"},
{"nomeCategoria":"Ingegneria","costoCategoria":"275000"},
{"nomeCategoria":"Edilizia","costoCategoria":"328000"}]", true);

// in this case i will try to use tmp variable
$var1 = '';
$var2 = '';

// using for loop to match same value
for ($i;$i < sizeof($data);$i++) {
  if ($data[$i]['nomeCategoria'] == 'Ingegneria') {
    $var1 = $var1 + $data[$i]['costoCategoria'];
  } else {
    $var2 = $var2 + $data[$i]['costoCategoria'];
  }
}