2014-04-04 83 views
0

I'm具有以下陣列(僅原始尺寸的部分):PHP創建從陣列陣列,其中值等於

Array 
(
    [0] => Array 
     (
      [select_name] => cloudy 
      [table_source] => rush 
      [area] => land 
     ) 

    [1] => Array 
     (
      [select_name] => sunny 
      [table_source] => rush 
      [area] => land 
     ) 

    [2] => Array 
     (
      [select_name] => rainy 
      [table_source] => rush 
      [area] => land 
     ) 

    [3] => Array 
     (
      [select_name] => hi 
      [table_source] => calm 
      [area] => mountain 
     ) 

    [4] => Array 
     (
      [select_name] => low 
      [table_source] => calm 
      [area] => mountain 
     ) 

    [5] => Array 
     (
      [select_name] => medium 
      [table_source] => calm 
      [area] => mountain 
     ) 

如何合併此陣列,其中相對於其它的陣列區域的名字是相同的,以得到[區域]

通緝的結果與鍵名唯一的select_names:

Array 
(
    [land] => Array 
     (
      [0] => cloudy 
      [1] => sunny 
      [2] => rainy 
     ) 

    [mountain] => Array 
     (
      [0] => hi 
      [1] => low 
      [2] => medium 
     ) 

) 

在這裏找到我嘗試差:

$ar1 = array(array("select_name"=>"cloudy","table_source"=>"sunny","fachdaten_name"=>"rainy")); 
$ar2 = array(array("select_name"=>"hi","table_source"=>"low","fachdaten_name"=>"medium")); 

$good = array("select_name"); 


$ar1 = array_intersect($good, $ar1); 
$ar2 = array_intersect($good, $ar2); 

$result = array_merge_recursive($ar1, $ar2); 


echo "<pre>"; 
print_r($result); 
echo "</pre>"; 

感謝您的幫助,T本書

+0

所以,你有很多陣列,不僅是一個喜歡你的樣品? –

+0

對,數組的數量可能會有所不同(數據庫輸出行越多,數組越多) –

+0

爲什麼在你的代碼中你的數組沒有'area'鍵? –

回答

0

它可能不是最完美的解決方案,但你可以做到這一點

$aSelectNames = array(); 

//Loop through the first array 
foreach($aSelect as $select){ 
    if(!isset($aSelectNames[$select['area']])) { 
     $aSelectNames[$select['area']] = array(); 
    } 

    //Avoid duplicates 
    if(!in_array($select['select_name'], $aSelectNames[$select['area']])) { 
     $aSelectNames[$select['area']][] = $select['select_name'] 
    } 
} 
+0

感謝帕特爾,如果第一個foreach循環不是foreach($ aSelectNames爲$ select)? –

+0

@tBook不,它應該是無論你的第一個數組被稱爲'$ aSelectNames'是你想要建立的數組 – Pattle

+0

嗨帕特,感謝您的解決方案。它爲我工作,但我最好改變sql查詢來解決那裏的問題string_agg和union all。 –