【问题标题】:Merge array with varying key value pairs合并具有不同键值对的数组
【发布时间】:2016-06-08 15:04:26
【问题描述】:

所以我有各种数组,它们并不总是有相同的键/值对。我想要做的是能够合并数组,但是如果它们在该数组中尚不存在,则添加空键/值对,但在其他数组中添加。这很难解释,但这可能会更好地解释它:

$arrayOne = array('name' => 'rory', 'car' => 'opel');
$arrayTwo = array('name' => 'john', 'dog' => 'albert');

我需要以某种方式把它变成:

$finalArray = array(
    array('name' => 'rory', 'car' => 'opel', 'dog' => ''),
    array('name' => 'john', 'car' => '', 'dog' => 'albert')
);

我一直在查看 PHP 的文档,但找不到任何可以为我做这件事的东西。谁能指出我正确的方向?我什至不知道我想在这里实现什么的合适搜索词,“数组合并”不够具体。

【问题讨论】:

  • 所以首先你想知道每个子数组在结果中应该有哪些键。为此,您可以获取每个数组的键(array_keys())并将它们组合成一个数组(array_merge() + array_unique())。然后,您可以使用包含所有键的数组将每个数组放入最终数组并填写您拥有的值(array_replace())。

标签: php arrays


【解决方案1】:
<?php
$arrayOne = array('name' => 'rory', 'car' => 'opel');
$arrayTwo = array('name' => 'john', 'dog' => 'albert');

$diff1=array_diff(array_flip($arrayOne), array_flip($arrayTwo));
$diff2=array_diff(array_flip($arrayTwo), array_flip($arrayOne));
//array_flip flips the key of array with value
//array_diff would return the values in the first array that are not present in any of the other arrays inside

foreach ($diff2 as $s) {
    $arrayOne[$s]="";
}
foreach ($diff1 as $s) {
    $arrayTwo[$s]="";
};
//set key that didn't exist in that array as ""

$finalArray[]=$arrayOne;
$finalArray[]=$arrayTwo;
//add the arrays to the final array

print_r($finalArray);

【讨论】:

    【解决方案2】:

    我会这样做:

    1. 使用array_merge 将单独的数组合并为一个(合并为一个临时变量)
    2. 使用array_keys获取这个新数组的唯一键
    3. 对于每个单独的数组,循环遍历新的键数组,并为不在数组中的每个键添加一个空值。然后将单独的数组推入最终数组。

    【讨论】:

    • 谢谢,我就是这样做的,而且效果很好,已将其发布为答案,以防它对其他人有所帮助。
    【解决方案3】:
    <?php
    $arrayOne = array('name' => 'rory', 'car' => 'opel');
    $arrayTwo = array('name' => 'john', 'dog' => 'albert');
    $new = array_merge($arrayOne,$arrayTwo);
    $new = array_keys($new);
    $newarray = array();        
    foreach($new as $value){            
    $newarray[0][$value] = isset($arrayOne[$value]) ? $arrayOne[$value] :  '' ;
    $newarray[1][$value] = isset($arrayTwo[$value]) ? $arrayTwo[$value] :  '' ;         
            }
            echo "<pre>";print_r($newarray);
    

    您也可以使用这个简短的答案

    $arrayOne = array('name' => 'rory', 'car' => 'opel');
    $arrayTwo = array('name' => 'john', 'dog' => 'albert');
    $defaults = array('name' => '','car'  => '','dog' => '');
    $arrayOne += $defaults;
    $arrayTwo += $defaults;
    $newarray = array($arrayOne,$arrayTwo);
    echo "<pre>";print_r($newarray);
    

    【讨论】:

      【解决方案4】:

      根据 Justin Powell 概述的内容,我设法在发布其他两个代码示例之前想出了这段代码(感谢 mamta 和 user6439245)。

      我还需要获取包含数字的键并对它们进行适当的排序,否则我的键会像 employer_1, education_1, employer_2, education_2 那样被索引。

      // get the initial form entries data
      $entries = array(
          array('name' => 'john', 'car' => 'fiat', 'employer_1' => 'tangerine', 'education_1' => 'hideaways', 'education_2' => 'extras'),
          array('name' => 'rory', 'car' => 'opel', 'employer_1' => 'sagittarius', 'employer_2' => 'tangerine', 'employer_3' => 'thehideout', 'education_1' => 'knatchbull')
      );
      
      
      // create an empty array to populate with all field keys
      $mergedKeys = array();
      
      // push all field keys into the array
      foreach($entries as $entry){
          foreach($entry as $key => $value){
              array_push($mergedKeys, $key);
          }
      }
      
      // remove duplicate keys from the array
      $uniqueMergedKeys = array_unique($mergedKeys);
      
      // create a new array to populate with the field keys we need to sort - the ones with numbers in
      $keysToSort = array();
      
      // push the number-containing keys into the array
      $i=0;
      foreach($uniqueMergedKeys as $uniqueKey){
          if(1 === preg_match('~[0-9]~', $uniqueKey)){
              array_push($keysToSort, $uniqueKey);
          }
          $i++;
      }
      
      // remove the number containing keys from the unique keys array
      $uniqueMergedKeys = array_diff($uniqueMergedKeys, $keysToSort);
      
      // sort the keys that need sorting
      sort($keysToSort);
      
      // put the newly sorted keys back onto the original keys array
      foreach($keysToSort as $key){
          array_push($uniqueMergedKeys, $key);
      }
      
      $final = array();
      
      $i = 0;
      foreach($entries as $entry){
      
          foreach($uniqueMergedKeys as $key){
              //if($entries[$i][$key]){
              if (array_key_exists($key, $entries[$i])) {
                  $final[$i][$key] = $entries[$i][$key];
              } else {
                  $final[$i][$key] = '';
              }
          }
      
          $i++;
      }
      
      echo '<pre>'; print_r($final); echo '</pre>';
      

      【讨论】:

      • 我认为 $entries[$i][$key][0];是一个错字,除非您只想存储子数组值的第一个字母
      • 公平点,真正的数据实际上来自 WordPress,而值,即 'john' 实际上是像 array('john') 这样的单行数组 - 已编辑,谢谢 :)
      猜你喜欢
      • 2016-12-29
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      • 2018-05-22
      • 1970-01-01
      相关资源
      最近更新 更多