2016-09-21 112 views
0

很長時間無法解決smth看起來很簡單的問題...我想合併一個二維數組。 的例子:在PHP中合併二維數組

$arr1 = { 
    [532] = 
    { 
    [0] = "11" 
    [1] = "12" 
    } 
    [273] = 
    { 
    [0] = "99" 
    } 
} 
$arr2 = { 
    [532] = 
    { 
    [0] = "11" 
    [1] = "13" 
    } 
} 

和合並的結果應該是,在地圖上常見的按鍵,完全一樣的陣列:

$result = { 
    [532] = 
    { 
    [0] = 
    {  
     [0] = "11" 
     [1] = "12" 
    } 
    [1] = 
    { 
     [0] = "11" 
     [1] = "13" 
    } 
    } 
    [273] 
    [0] = 
    {  
     [0] = "99" 
    } 
    [1] = 
    { 

    } 
} 

我嘗試sometihng這樣的:

$result = $arr1; 
    foreach ($arr2 as $key => $value) { 
     $result[$key] = isset($result[$key]) ? array_merge([$result[$key]], [$value]) : [$value]; 
    } 

但它不工作,如果$ arr2是空的:(

+0

你是什麼意思'如果$ arr2是空的'。如果你沒有第二個數組,爲什麼要合併? – jitendrapurohit

回答

1

可能是這樣的

$arr1 = { 
     [532] = 
     { 
     [0] = "11" 
     [1] = "12" 
     } 
     [273] = 
     { 
     [0] = "99" 
     } 
    } 
    $arr2 = { 
     [532] = 
     { 
     [0] = "11" 
     [1] = "13" 
     } 
    } 

    $newarray = array(); 
    foreach ($arr1 as $key => $value) { 
     $cu = $arr1[$key]; 

     $newarray[$key][] = $cu; 

     if(!isset($arr2[$key])) { 
      $newarray[$key][] = array(); 
     } 
     else { 
     $newarray[$key][] = $arr2[$key]; 
     } 
    } 

foreach ($arr2 as $key => $value) { 
      if(!isset($newarray[$key])) { 
      $newarray[$key][] = $arr2[$key]; 
      } 
     } 
+1

Arg,你的權利 - 想想我現在已經有了 - 沒有f5按鈕就有點棘手! –

+0

看看你在哪裏用它 - 好吧 –

+0

好吧,但如果第一個數組將是空的呢?我總是想要像例子那樣得到結構數組 –

1

對於第二陣列檢查,則需要使用isset()任一陣列設置或不:

實施例:

<?php 
$arr1 = array('532'=>array('11','12'),'273'=>array('99')); 
$arr2 = array('532'=>array('11','13')); 

$newArr = array(); 
foreach ($arr1 as $key => $value) { 
    if(isset($arr2[$key])){ 
     $newArr[$key][] = $value; 
     $newArr[$key][] = $arr2[$key]; 
    } 
    else{ 
     $newArr[$key] = $value; 
    } 
} 
echo "<pre>"; 
print_r($newArr); 
?> 

結果:

Array 
(
    [532] => Array 
     (
      [0] => Array 
       (
        [0] => 11 
        [1] => 12 
       ) 

      [1] => Array 
       (
        [0] => 11 
        [1] => 13 
       ) 

     ) 

    [273] => Array 
     (
      [0] => 99 
     ) 

) 

更進一步,我F你想合併這兩個相同的索引比你可以使用array_merge()一些東西像:

<?php 
$arr1 = array('532'=>array('11','12'),'273'=>array('99')); 
$arr2 = array('532'=>array('11','13')); 

$newArr = array(); 
foreach ($arr1 as $key => $value) { 
    if(isset($arr2[$key])){ 
     $newArr[$key][] = array_merge($value,$arr2[$key]);  
    } 
    else{ 
     $newArr[$key] = $value; 
    } 
} 
echo "<pre>"; 
print_r($newArr); 
?> 

結果:

Array 
(
    [532] => Array 
     (
      [0] => Array 
       (
        [0] => 11 
        [1] => 12 
        [2] => 11 
        [3] => 13 
       ) 

     ) 

    [273] => Array 
     (
      [0] => 99 
     ) 

) 

需要注意的是,IST腳本,會給你造成的,你需要獨特的索引。 第二個腳本將爲您提供一個數組中的所有值。