how can i show php array multiplying in loop I have to show in the foreach so that I can add mysql
$data = [
[
"id" => "3202",
"total" => "5"
],[
"id" => "3190",
"total" => "2"
],[
"id" => "3199",
"total" => "5"
]
];
foreach($data as $v){
//$v["total"]*
//output = 5x2x5= 50
}
CodePudding user response:
You can use array_column and array_product in this problem:
<?php
$data = [
['id' => '3202','total' => '5'],
['id' => '3190','total' => '2'],
['id' => '3199','total' => '5']
];
$total = array_column($data, 'total');
$product = array_product($total);
printf('The product of total: %s', $product);
CodePudding user response:
<?php
$data = [
['id' => '3202','total' => '5'],
['id' => '3190','total' => '2'],
['id' => '3199','total' => '5']
];
$total = 1; // empty product
$output = [];
foreach($data as $v) {
$total *= $v['total'];
$output[] = $v['total'];
}
echo implode('x', $output) . '= ' . $total; // 5x2x5= 50
Might want to also add logic to check if the $data is empty first with count($data), then when the list is empty, output a message instead.
