Merge the sub array if it has the save id value?

Posted by sophie on Stack Overflow See other posts from Stack Overflow or by sophie
Published on 2012-09-12T21:36:15Z Indexed on 2012/09/12 21:38 UTC
Read the original article Hit count: 285

I have an array and I want to merge the sub array that have the same id value together:

    <?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>';    
?>

I GOT:

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

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

)

BUT WHAT I WANT IS :

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

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

)

Anyone could tell me how to do this? thanks

© Stack Overflow or respective owner

Related posts about arrays

Related posts about php5