以数学方式添加两个多维数组的最有效方法?

时间:2013-03-07 15:28:06

标签: php arrays algorithm math

考虑两个简单的数组:

<?php
  $array1 = array(
    'blue' => 5,

    'green' => array(
      'square' => 10,
      'sphere' => 0.5,
      'triangle' => 3
    ),

    'red' => array(
      'circle' => 1000,
    ),

    'black' => 4,

  );

  $array2 = array(
    'blue' => 1,

    'green' => array(
       'square' => 11,
       'circle' => 5,
    ),

    'purple' => 10,

    'yellow' => array(
      'triangle' => 4
    ),

    'black' => array(
      'circle' => 6,
    ),

  );

我需要以递归的方式以数学方式相加,每个值$array1$array2

  • 保留密钥
  • 如果某个密钥在$array1中不存在但在$array2中存在,则最终数组将只包含$array2的值(反之亦然)
  • 如果两者都存在,则会添加数值+
  • 不会触及非数字值
  • 如果$array1上的值指向另一个子数组,并且$array2中的值指向一个值,则结束值将导致该键包含一个包含{{{1}值的子数组。 1}}使用父名称及其值加上新的键/值(参见示例中的$array1
  • 应该可以在几乎无限制的嵌套中工作

澄清,例如如果我们说

black

这对我来说似乎非常令人生畏。我知道我可以循环遍历一个数组并轻松地递归添加值,我有点工作(有点),但是当我进入特殊规则(例如<?php $final = array_merge_special($array1, $array2); // We would end up with, if you var_export()'d final, something like: // (Note: Hope I didn't make mistakes in this or it will be confusing, // so expect mild human error) $final = array( 'blue' => 6, // 5+1 'green' => array( 'square' => 21, // (10+11) 'sphere' => 0.5, // only in $array1 'triangle' => 3 // only in $array1 'circle' => 5, // only in $array2 ), 'purple' => 10, // only in $array2 'yellow' => array( // only in $array2 'triangle' => 4 ), 'red' => array( // only in $array1 'circle' => 1000, ), 'black' => array( 'circle' => 6, // untouched, while $black is present in both, the $array1 value does not have a 'circle' key, and is actually only a key/value (see below) 'black' => 4, // the key/value from $array1 that was not a subarray, even though it was a subarray in $array2 ), ); 的那些)时,我甚至无法想象一下破解代码的样子。必须有一种方法可以单独循环遍历每个数组并black'合并值?

1 个答案:

答案 0 :(得分:1)

您将使用array_walk_recursive(请参阅:See php Manual here)并可能使用array_merge_recursive。我必须进一步思考才能全面了解。

好的,确定这不起作用! Array_walk_recursive不会将包含数组的键传递给函数。这个问题一直在我的大脑中流动,所以我只需要编写一个功能来完成它!这是:

function dosum($arin) {
  $arout = array();
  foreach ($arin as $key1 => $item1) {
    $total = 0;
    if(is_array($item1)) {
      foreach($item1 as $key2 => $item2) {
        if(is_numeric($key2))
          $total += $item2;
        else
          if(is_array($item2))
            $arout[$key1] = dosum(array($key2 => $item2));
          else
            $arout[$key1][$key2] =$item2;
      }
      if($total)
        if(isset($arout[$key1]))
          $arout[$key1][$key1] = $total;
        else
          $arout[$key1] = $total;
      }
    else
      $arout[$key1] = $item1;    
    }
  return $arout;
  }

对于给出的2个数组,你可以像这样使用它:

print_r(dosum(array_merge_recursive($array1, $array2)));