我需要在PHP中创建一个关于市场的3D阵列。我已经完成了创建工作,用市场名称作为一个数组,产品作为第二个数组,每个月的金额作为第三个数组。我把市场名称作为一个数组,产品作为第二个数组,每个月的金额作为第三个数组。现在我需要把市场中的所有产品加起来。例如,我需要把市场中的所有产品加起来。
bread = 126100
所有市场的所有面包数量之和。
我将分享我的代码。
$market = array(
"1" =>array
("bread"=>array(1000,6000,1550,2000,4000,6550,7000,4000,7000,1000,2000,3000),
"milk"=>array(3000,4000,5000,6000,5000,4000,7000,6000,7000,4000,2000,5000),
"cheese"=>array(2000,3000,2000,1000,4000,3000,3000,5000,4000,3000,4000,4000),
"juice "=>array(2000,4000,5000,4000,3000,4000,1000,1000,1000,2000,1000,2000)),
"2" => array
("bread"=>array(3000,3000,4000,3000,6000,6000,4000,3000,4000,3000,6000,6000),
"milk"=>array(6000,3000,4000,5000,4000,3000,5000,4000,3000,5000,6000,5000),
"cheese"=>array(3000,3000,3000,5000,2000,2000,3000,4000,4000,3000,2000,1000),
"juice"=>array(1000,1000,4000,3000,3000,1000,2000,2000,1000,1000,4000,3000)),
"3"=> array
("bread"=>array(7000,4000,3000,2000,2000,2000,4000,2000,1000,1000,1000,1000),
"milk"=>array(3000,3000,2000,2000,1000,2000,3000,2000,2000,2000,1000,1000),
"cheese"=>array(1000,1000,2000,2000,2000,3000,2000,3000,3000,2000,1000,1000),
"juice"=>array(1000,900,900,1000,2000,2000,1000,1000,2000,3000,1000,900))
);
我已经尝试过这样的东西,但没有完全按照我的要求工作。
function searchItemsByKey($array, $key)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && key($array)==$key)
$results[] = $array[$key];
foreach ($array as $sub_array)
$results = array_merge($results, searchItemsByKey($sub_array, $key));
}
return $results;
}
$results =searchItemsByKey($market, 'bread');
print_r($results);
$total = [];
foreach ($market as $key => $value) {
foreach ($value as $product => $prices) {
$total[$key][$product]['total'] = array_sum($prices);
}
}
print_r($total); exit;
在上面的代码中。$key
是市场。$product
是产品名称,而 total
是产品在该市场的总价值。
您可以使用 array_sum()
PHP官方文档。PHP array_sum
做到这一点,你就会得到你的市场明智的总产品。然后,你会得到你的市场化的总产品。
$marketProducts = [];
foreach ($market as $key => $products) {
foreach ($products as $name => $amount) {
$marketProducts[$key][$name] = array_sum($amount);
}
}
dd($marketProducts);