合并子数组是否具有保存标识值?

时间:2012-09-12 21:36:16

标签: php arrays multidimensional-array

我有一个数组,我想合并具有相同id值的子数组:

    <?php 
        $a = Array(
        Array
            (
            "id" => 1,
            "id_categorie" => 1,
            "nb" => 18
           ),
           Array
           (
            "id" => 1,
            "id_categorie" => 8,
            "nb" => 14
         ),
        Array
        (
            "id" => 2,
            "id_categorie" => 10,
            "nb" => 15
        )

);
$result = array();

foreach ($a as $k=>$v){

    $result[$v['id']] =$v; 


}

echo '<pre>';
print_r($result);
echo '</pre>';    
?>

我GOT:

Array
(
    [1] => Array
        (
            [id] => 1
            [id_categorie] => 8
            [nb] => 14
        )

    [2] => Array
        (
            [id] => 2
            [id_categorie] => 10
            [nb] => 15
        )

)

但我想要的是:

Array
(
    [1] => Array
        (
             Array
          (                   
                "id_categorie" => 1,
                "nb" => 18
           ),
         Array
         (                
             "id_categorie" => 8,
             "nb" => 14
         )
      )

    [2] => Array
        (
            [id_categorie] => 10
            [nb] => 15
        )

)

任何人都可以告诉我该怎么做?感谢

1 个答案:

答案 0 :(得分:1)

试试这个:

$result = array();
foreach ($a as $arr) {
    // unset the 'id' index; it becomes the array's index instead
    $id = $arr['id'];
    unset($arr['id']);
    if (!isset($result[$id])) {
        // add the new item as a top-level element
        $result[$id] = $arr;
    } else if (isset($result[$id]['id_categorie'])) {
        // the current 'id' is set as a top-level element; convert it
        // into a sub-array and also add the new element to it
        $new = array($result[$id], $arr);
        $result[$id] = $new;
    } else {
        // we already have a sub-array of items; add the new element
        $result[$id][] = $arr;
    }
}

它应该产生你想要的输出,虽然未经测试/等。如果id未被发现,则会将该完整元素添加到$result数组中。如果之前只遇到id ,它会将之前的实例转换为数组,并将新实例添加到数组中。同一id的所有其他实例也将添加到该数组中。