从数组中检索值,然后将其添加到新的PHP中

时间:2014-06-17 12:53:55

标签: php arrays

我有很大的问题,因为我不知道如何从这个数组获取值,其中值是新数组的关键。这是我的源数组

Array
(
     [0] => Array
        (
            [ID] => 250602
            [NAME] => qwe
        )

    [1] => Array
        (
            [ID] => 250603
            [NAME] => wer
        )

    [2] => Array
        (
            [ID] => 250629
            [NAME] => sdf
        )

    [3] => Array
        (
            [ID] => 250629
            [NAME] => xcv
        )

    [4] => Array
        (
            [ID] => 250629
            [NAME] => fghfgh
        )

    [5] => Array
        (
            [ID] => 250601
            [NAME] => pggd
        )

    [6] => Array
        (
            [ID] => 250601
            [NAME] => dfgdfg
        )

    [7] => Array
        (
            [ID] => 250606
            [NAME] => dfgdfg
        )
)

当id相同时,将创建一个看起来像id = 250629

的新表
[NAME] => Array
        (
            [0] => sdf
            [1] => xcv
            [2] => fghfgh
        )

2 个答案:

答案 0 :(得分:1)

这样的foreach循环怎么样?

<?php
$final_array=array();
foreach($arrays as $sub_arr){ //it will traverse loop for all sub-arrays
    $final_array[$sub_arr['ID']][]=$sub_arr['NAME'];       
}
print_r($final_array); //you should see expected output.
?>

它将在输出下为您的给定数据产生:

Array
(
    [250602] => Array
        (
            [0] => qwe
        )

    [250603] => Array
        (
            [0] => wer
        )

    [250629] => Array
        (
            [0] => sdf
            [1] => xcv
            [2] => fghfgh
        )

    [250601] => Array
        (
            [0] => pggd
            [1] => dfgdfg
        )

    [250606] => Array
        (
            [0] => dfgdfg
        )

)

Working Demo

答案 1 :(得分:1)

喜欢这个

$by_name = array();
foreach($your_array as $item)
    $by_name[$item['ID']] []= $item['name'];

这使用了php的惰性数组初始化([]=隐式创建了一个新数组。)

如果从mysql获取数组,您可能还会考虑GROUP_CONCAT