3 回答
TA贡献1898条经验 获得超8个赞
如果您的数组结构始终与您发布的相同,那么此代码将为您工作:
$example_array = array(
array( '0' => 32.00 ),
array( '2' => 32.00 ),
array( '2' => 32.00 )
);
$new_array = array();
// loop through every item in nested foreach
foreach( $example_array as $value ) {
foreach( $value as $key => $number ) {
// if the array key not exist, calculate with 0, otherwise calculate with the actual value
$new_array[$key] = isset($new_array[$key]) ? $new_array[$key] + $number : 0 + $number;
}
}
print_r( $new_array );
// prints Array ( [0] => 32 [2] => 64 )
您的数组的代码示例:
$shippingPrice = array();
// loop through every item in nested foreach
foreach( $minmaxarray as $value ) {
foreach( $value as $key => $number ) {
// if the array key not exist, calculate with 0, otherwise calculate with the actual value
$shippingPrice[$key] = isset($shippingPrice[$key]) ? $shippingPrice[$key] + $number : 0 + $number;
}
}
echo '<pre>';
print_r( $shippingPrice );
TA贡献1851条经验 获得超4个赞
你可以试试这段代码
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach($array as $key=> $value){
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}
您通过数组调用此函数,然后函数将返回您预期的数组。
array_flatten($array);
TA贡献1871条经验 获得超8个赞
您可以使用array_walk_recursive
而不是 2foreach
循环
array_walk_recursive($arr, function($v,$k) use (&$r){ $r[$k] = isset($r[$k]) ? ($r[$k]+$v) : $v; });
工作演示:- https://3v4l.org/MMDEv
- 3 回答
- 0 关注
- 79 浏览
添加回答
举报