3

考虑两个简单的数组:

<?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(反之亦然)
  • 如果两者都存在,则将添加数值+
  • 不会触及非数字值
  • 如果 on 上的值$array1指向另一个子数组,并且在$array2其中指向一个值,则最终值将导致该键包含一个子数组,该子数组包含来自的值$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
    ),

  );

这对我来说似乎令人生畏。我知道我可以遍历一个数组并轻松地递归地添加值,并且我有这个工作(有点),但是当我进入特殊规则(例如 for 的规则black)时,我什至无法想象代码会如何损坏看。必须有一种方法可以单独循环每个数组并将unset()值合并?

4

1 回答 1

1

您将使用 array_walk_recursive(请参阅:请参阅此处的 php 手册)和可能的 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)));
于 2013-03-07T15:48:26.600 回答