Using Category to add the same kind and display

Viewed 20

So the result of the code is:

Hotel: 20
Hotel: 210
Food: 29.04
Fuel: 186
Food: 55

Array ( 
    [0] => Array ( [Category] => Hotel [Price] => 10 [Quantity] => 2 ) 
    [1] => Array ( [Category] => Hotel [Price] => 70 [Quantity] => 3 ) 
    [2] => Array ( [Category] => Food [Price] => 1.21 [Quantity] => 24 ) 
    [3] => Array ( [Category] => Fuel [Price] => 31 [Quantity] => 6 ) 
    [4] => Array ( [Category] => Food [Price] => 5.5 [Quantity] => 10 ) 
)

As you can see i multiplied the quantity and price and now i want the category of the same type to be added like:

Hotel: 230
Food: 84.04
Fuel: 186

But i keep having the problem of string + int (or something like that). So guide me what i am doing wrong. Following is the code:

<!DOCTYPE html>
<html>
  
<body>
    <center>
        <h1>DISPLAY DATA PRESENT IN CSV</h1>
        <h3>CSV File</h3>
  
        <?php
        echo "<html><body><center><table>\n\n";
        // $fileName = $_POST['csvfile'];
        // $fileName = "./test.csv";
        // $summary = array();
        $i = 0;
        // $index = null;

        // $file = fopen($fileName, "r");

        $array = $fields = array();
        $handle = @fopen("test.csv", "r");
        if($handle){
            while(($row = fgetcsv($handle, 4096)) !== False){
                if(empty($fields)){
                    $fields = $row;
                    continue;
                }
                foreach($row as $k=>$value){
                    $array[$i][$fields[$k]] = $value;
                }
                $i++;
            }
            if(!feof($handle)){
                echo "Error: unexpected fgets() fail\n";
            }
            fclose($handle);
        }
        foreach($array as $key => $value){
            for($a = 0; $a < 1; $a++){
                if($value['Category'] == $value['Category']){
                    echo $value['Category'] . ": " . ($value['Quantity'] * $value['Price']) . "<br>";
                }
                else{
                echo $value['Category'] . ": " . ($value['Quantity'] * $value['Price']) . "<br>";
                }
            }
        }
        echo "<br>";
        print_r($array);

        $sumArray = array();
        foreach($array as $k=>$subArray){
            foreach($subArray as $key=>$value){
                $sumArray['Category'] += $value;
            }
        }
        print($sumArray);

        echo "\n</table></center></body></html>";
        ?>
    </center>
</body>
  
</html>
1 Answers

You need to multiply the price and the quantity when creating $sumArray.

$sumArray = [];
foreach ($array as $value) {
    $cat = $value['Category'];
    if (!isset($sumArray[$cat])) {
        $sumArray[$cat] = 0;
    }
    $sumArray[$cat] += $value['Price'] * $value['Quantity'];
}
Related