php从数组中创建数组,其中值相等

时间:2014-04-04 09:06:43

标签: php arrays

我有以下数组(只是原始大小的一部分):

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>";

感谢您的帮助,请预订

1 个答案:

答案 0 :(得分: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']
    }
}