PHP Question

How to add duplicates in array in one row

I have this array:

Array(
[0] => Array(
[0] => 1
[1] => Name1
[2] => Ingridient1
)
[1] => Array(
[0] => 2
[1] => Name2
[2] => Ingridient1
)
[2] => Array(
[0] => 2
[1] => Name2
[2] => Ingridient2
)
)


How can I add in one key the duplicates like Name2 to have Ingridient1 and Ingridient2...IngridientN?

Answer
<?php

$my_arr = array(array(1, 'Name1', 'Ingredient1'), array(2, 'Name2', 'Ingredient1'), array(2, 'Name2', 'Ingredient2') );


$my_final_array = array();

foreach($my_arr as $val){
    if (!isset($my_final_array[$val[1]])){
        $my_final_array[$val[1]] = array();
    }

    if (!in_array($val[2], $my_final_array[$val[1]])){
        $my_final_array[$val[1]][] = $val[2];
    }    
}
echo '<pre>';
print_r($my_final_array);
echo '</pre>';
?>

Output:

Array
(
    [Name1] => Array
        (
            [0] => Ingredient1
        )

    [Name2] => Array
        (
            [0] => Ingredient1
            [1] => Ingredient2
        )

)
Comments