我有这个数组:
WHERE meta_key LIKE '_sku'
如何在一个键中添加像Name2这样的重复项来使Ingridient1和Ingridient2 ... IngridientN?
答案 0 :(得分:0)
<?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>';
?>
输出:
Array
(
[Name1] => Array
(
[0] => Ingredient1
)
[Name2] => Array
(
[0] => Ingredient1
[1] => Ingredient2
)
)
如何回应:
echo '<pre>';
foreach($my_final_array as $name => $ingredients){
echo $name . ' - Ingredients: ' . implode(', ', $ingredients).PHP_EOL;
}
echo '</pre>';
回声输出:
Name1 - Ingredients: Ingredient1
Name2 - Ingredients: Ingredient1, Ingredient2
答案 1 :(得分:0)
@mani答案的小改动
$array = array(array(1, 'Name1', 'Ingredient1'), array(2, 'Name2', 'Ingredient1'), array(2, 'Name2', 'Ingredient2') );
$final_array = array();
foreach($array as $val){
$final_array[$val[1]][] = $val[2];
}