数组合并递归php

时间:2013-06-13 09:32:18

标签: php arrays

任何人都可以告诉我如何使用php数组操作将第一个数组转换为第二个数组。

第一个数组: -

Array
(
    [0] => Array
        (
            [actual_release_date] => 2013-06-07 00:00:00
            [distributors] => 20th Century Fox / 20th Century Fox Animation / Fox 2000 Pictures / Fox Searchlight
        )

    [1] => Array
        (
            [actual_release_date] => 2013-06-28 11:11:00
            [distributors] => 20th Century Fox / 20th Century Fox Animation / Fox 2000 Pictures / Fox Searchlight
        )
)

第二个数组: -

Array
(
    [0] => Array
        (
            [actual_release_date] => array( 0=>2013-06-07 00:00:00 , 1=> 2013-06-28 11:11:00 )
            [distributors] => 20th Century Fox / 20th Century Fox Animation / Fox 2000 Pictures / Fox Searchlight
        )
)

如果第二个元素是常见的,并且第一个元素不同,那么我们必须将它组合在一个数组中。

提前致谢。

2 个答案:

答案 0 :(得分:2)

您可以使用array_reduce

$data = array_reduce($data, function ($a, $b) {
    if (isset($a[$b['distributors']])) {
        $a[$b['distributors']]['actual_release_date'][] = $b['actual_release_date'];
    } else {
        $a[$b['distributors']]['actual_release_date'] = array($b['actual_release_date']);
        $a[$b['distributors']]['distributors'] = $b['distributors'];
    }
    return $a;
}, array());

print_r(array_values($data));

输出

Array
(
    [0] => Array
        (
            [actual_release_date] => Array
                (
                    [0] => 2013-06-07 00:00:00
                    [1] => 2013-06-28 11:11:00
                )

            [distributors] => 20th Century Fox / 20th Century Fox Animation / Fox 2000 Pictures / Fox Searchlight
        )

)

See Live DEMO

答案 1 :(得分:-1)

你尝试尝试阵列marge ..

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
//Maerge them
$result = array_merge($array1, $array2);
print_r($result);
?>

以上示例将输出:

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

了解详情here

文档说:

  

如果要将第二个数组中的数组元素追加到   第一个数组,而不是覆盖第一个数组中的元素   而不是重新索引,使用+数组联合运算符:

<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);
?>
  

将保留第一个数组中的键。如果是数组键   存在于两个数组中,那么第一个数组中的元素将是   使用和第二个数组中的匹配键元素   忽略。

array(5) {
  [0]=>
  string(6) "zero_a"
  [2]=>
  string(5) "two_a"
  [3]=>
  string(7) "three_a"
  [1]=>
  string(5) "one_b"
  [4]=>
  string(6) "four_b"
}
相关问题