如何将数组合并到另一个数组的子级别(递归)?

时间:2018-05-16 18:07:51

标签: php arrays multidimensional-array merge

ARRAY1:

array(1) {
  [0]=>
  array(2) {
    ["1234"]=>
    array(1) {
      ["fileName"]=>
      string(10) "monkey.jpg"
    }
    ["3456"]=>
    array(1) {
      ["fileName"]=>
      string(9) "horse.jpg"

    }
  }
}

数组2:

array(2) {
  ["number"]=>
  string(2) "62"
  ["company"]=>
  string(7) "animals"
}

我想将两个数组合并在一起:

$result = array_merge_recursive($array1,$array2);

结果如下:

array(3) {
  [0]=>
  array(2) {
    ["1234"]=>
        array(1) {
          ["fileName"]=>
          string(10) "monkey.jpg"
        }
     ["3456"]=>
        array(1) {
          ["fileName"]=>
          string(9) "horse.jpg"   
     }
  }
  ["number"]=>
  string(2) "62"
  ["company"]=>
  string(7) "animals"
}

但我真正需要的结果是:

array(1) {
  [0]=>
  array(4) {
     ["1234"]=>
          array(1) {
         ["fileName"]=>
          string(10) "monkey.jpg"
         }
      ["3456"]=>
         array(1) {
            ["fileName"]=>
           string(9) "horse.jpg"   
         }
      ["number"]=>
      string(2) "62"
      ["company"]=>
      string(7) "animals"
  }
}

我怎么能实现这个目标?

我测试了array_push RaymondNijland建议:

array_push($array1[0],$array2);

但现在$array1看起来像这样:

array(1) {
  [0]=>
  array(3) {
    ["1234"]=>
     array(1) {
     ["fileName"]=>
      string(10) "monkey.jpg"
       }
    ["3456"]=>
       array(1) {
        ["fileName"]=>
        string(9) "horse.jpg"   
      }
    }
    [0]=>
    array(2) {
        ["number"]=>
         string(2) "62"
         ["company"]=>
         string(7) "animals"
    }
  }
}

仍然不是我要找的结果

2 个答案:

答案 0 :(得分:1)

由于您要添加到现有数组,请遍历新数组并添加其中的每个元素。

这是功能和示例用法:

function array_merge_recursive_custom($array1, $array2){
    $result[] = $array1;

    foreach($array2 as $key=>$value){
        $result[0][$key] = $value;
    }
    return $result;
}

$array1 = ['1234' => ['fileName' => 'monkey.jpg'], '3456' => ['fileName' => 'horse.jpg']];
$array2 = ['number' => '62', 'company' => 'animals'];

$result = array_merge_recursive_custom($array1, $array2);

var_dump($result);

输出:

array(1) {
  [0]=>
  array(4) {
    [1234]=>
    array(1) {
      ["fileName"]=>
      string(10) "monkey.jpg"
    }
    [3456]=>
    array(1) {
      ["fileName"]=>
      string(9) "horse.jpg"
    }
    ["number"]=>
    string(2) "62"
    ["company"]=>
    string(7) "animals"
  }
}

答案 1 :(得分:1)

$array3 = $array1;
foreach ($array2 as $key => $value) {
  $array3[0][$key] = $value;
}