在PHP中对多维数组执行计算

时间:2019-06-14 09:34:02

标签: php arrays multidimensional-array

我有两个如下所示的多维数组,它们的结构相同,但值不同。

$first = array (
  'something1' => 
  array (
    '2019-06-14' => 0,
    '2019-06-13' => 0,
    '2019-06-12' => 0,
    '2019-06-11' => 1,
    '2019-06-10' => 1
  ),
  'something2' => 
  array (
    '2019-06-14' => 0,
    '2019-06-13' => 0,
    '2019-06-12' => 0,
    '2019-06-11' => 1,
    '2019-06-10' => 0
  ),
)

$second = array (
  'something1' => 
  array (
    '2019-06-14' => 8,
    '2019-06-13' => 4,
    '2019-06-12' => 7,
    '2019-06-11' => 2,
    '2019-06-10' => 9
  ),
  'something2' => 
  array (
    '2019-06-14' => 3,
    '2019-06-13' => 7,
    '2019-06-12' => 3,
    '2019-06-11' => 4,
    '2019-06-10' => 8
  ),
)

我都需要对两者进行简单的计算,结果将是这样的(每个日期来自$ first数组的值/来自$ second数组的值):

$result = array (
  'someting1' => 
  array (
    '2019-06-14' => 0/8,
    '2019-06-13' => 0/4,
    '2019-06-12' => 0/7,
    '2019-06-11' => 1/2,
    '2019-06-10' => 1/9
  ),
  'something2' => 
  array (
    '2019-06-14' => 0/3,
    '2019-06-13' => 0/7,
    '2019-06-12' => 0/3,
    '2019-06-11' => 1/4,
    '2019-06-10' => 0/8
  ),
)

我已经尝试过使用嵌套的foreach循环,并且可以显示所需的值,如下所示,但是当我在第二个数组中嵌套另一组foreach循环时,显然会产生过多的结果,将所有内容除以所有内容。

foreach($array1 as $sth => $v) {
    foreach($v as $date => $number) {
        echo $sth. ' data: ' . $date . ' number: ' . $number . '</br>';
    }
}

我该如何进行计算?

2 个答案:

答案 0 :(得分:1)

第二个数组不需要任何其他循环;您拥有键$sth$date,因此可以直接访问值:

foreach($array1 as $sth => $v) {
    foreach($v as $date => $number) {
        echo $sth. ' data: ' . $date . ' number: ' . $number . '</br>';
        echo 'second number: ' . $second[$sth][$date] . '</br>';
    }
}

请注意,您可能需要添加检查以查看键是否确实存在于第二个数组中。

答案 1 :(得分:1)

简单的foreach循环应该做到这一点:

foreach($first as $k => $arr) 
    foreach($arr as $date => $num)
        $result[$k][$date] = $num . " / " . $second[$k][$date];