2013-06-13 129 views
0

誰能告訴我怎樣可以使用PHP數組操作的第一陣列轉換爲第二陣列。陣列合併遞歸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 
     ) 
) 

如果第二元件是常見的,並且第一元件是不同的,那麼我們必須組它在一個陣列中。

在此先感謝。

+0

您是否嘗試過普通的老'用'if'內foreach'? – Jon

+0

如果這兩個領域都很普遍? –

+0

@傑克只有一個將在actual_release_date – Ajeesh

回答

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

+0

謝謝巴巴它工作:) – Ajeesh

-1

你試試陣列瑪吉..

<?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

文檔說:

如果您想要追加ar從第二陣列射線元素到 第一陣列而不是覆蓋從第一陣列 的元素和不能重新索引,使用+陣列union運算符:

<?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" 
}