2014-04-04 48 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。 –