2016-11-01 152 views
1

如何使用Array1和Array2來獲取想要的結果?重建陣列以從第二個陣列添加密鑰

數組1

array(
    (int) 0 => '37', 
    (int) 1 => '38' 
) 

數組2

array(
    (int) 0 => array(
     'ParentKey' => array(
      'ChildKey1' => '1', 
      'ChildKey2' => '2' 
     ) 
    ), 
    (int) 1 => array(
     'ParentKey' => array(
      'ChildKey1' => '1', 
      'ChildKey2' => '1' 
     ) 
    ) 
) 

通緝的結果

array(
    (int) 0 => array(
     'ParentKey' => array(
      'Array1Key' => 37, 
      'ChildKey1' => '1', 
      'ChildKey2' => '2' 
     ) 
    ), 
    (int) 1 => array(
     'ParentKey' => array(
      'Array1Key' => 37, 
      'ChildKey1' => '1', 
      'ChildKey2' => '1' 
     ) 
    ) 
    (int) 2 => array(
     'ParentKey' => array(
      'Array1Key' => 38, 
      'ChildKey1' => '1', 
      'ChildKey2' => '2' 
     ) 
    ), 
    (int) 3 => array(
     'ParentKey' => array(
      'Array1Key' => 38, 
      'ChildKey1' => '1', 
      'ChildKey2' => '1' 
     ) 
    ) 
) 

我已經試過幾件事情,但是這讓我最接近...

PHP

$data = array(); 
foreach($Array1 as $id) 
{ 
    foreach($Array2 as $Array1Result) 
    { 
     $data[]['ParentKey'] = array(
      'Array1Key' => $id, 
      $Array1Result['ParentKey'] 
     ); 
    } 
} 

結果

array(
    (int) 0 => array(
    'ParentKey' => array(
     'Array1Key' => '37', 
     (int) 0 => array(
      'ChildKey1' => '1', 
      'ChildKey2' => '2' 
     ) 
    ) 
), 
    (int) 1 => array(
    'ParentKey' => array(
     'Array1Key' => '37', 
     (int) 0 => array(
      'ChildKey1' => '1', 
      'ChildKey2' => '1' 
     ) 
    ) 
), 
    (int) 2 => array(
    'ParentKey' => array(
     'Array1Key' => '38', 
     (int) 0 => array(
      'ChildKey1' => '1', 
      'ChildKey2' => '2' 
     ) 
    ) 
), 
    (int) 3 => array(
    'ParentKey' => array(
     'Array1Key' => '38', 
     (int) 0 => array(
      'ChildKey1' => '1', 
      'ChildKey2' => '1' 
     ) 
    ) 
) 
) 
+2

,問題是... – useyourillusiontoo

+0

替換'陣列( 'Array1Key'=> $ ID,$ Array1Result [ 'ParentKey'])與'array_merge(陣列( 'Array1Key'=> $ ID)', $ Array1Result ['ParentKey'])' –

+0

@CharlotteDunois幾乎沒有。謝謝!我只需要在'$ data [] ['ParentKey'] =' – Draven

回答

2

你究竟是什麼你做什麼。你把一個數組放入數組中。但是你需要將兩個數組合並在一起。第一個是Array1Key,第二個是舊數組。你可以通過array_merge來實現。

$data = array(); 
foreach($Array1 as $id) 
{ 
    foreach($Array2 as $Array1Result) 
    { 
     $data[]['ParentKey'] = array_merge(
      array('Array1Key' => $id), 
      $Array1Result['ParentKey'] 
     ); 
    } 
}