谁能告诉我如何使用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
)
)
如果第二个元素是相同的,而第一个元素是不同的,那么我们必须将它们组合在一个数组中。
您可以使用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
)
)
参见Live DEMO
你试着试试数组。
<?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
)
点击这里了解更多
文档说:
如果要将第二个数组中的数组元素追加到第一个数组,同时不覆盖第一个数组中的元素不重新索引,使用+数组联合操作符:
<?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"
}