我需要以下阵列的帮助:
$outputarray = array(
array("id" => 2,"name" => "ProductName","comment" => array("best product comment 1","best product comment 2","best product comment 3"))
);
输出应为:
array_unique
我需要返回值数组的“注释”键
$outputarray = array(
array("id" => 2,"name" => "ProductName","comment" => "best product comment 3")
);
不起作用。 它给了我独特但不是那个评论数组。这只是给我注释键值的最后一个值 像下面一样
{{1}}
请帮帮我。
答案 0 :(得分:0)
您可以使用array_reduce
:
<?php
$input_array = [
['id' => 2, 'name' => 'ProductName', 'comment' => 'best product comment 1'],
['id' => 2, 'name' => 'ProductName', 'comment' => 'best product comment 2'],
['id' => 2, 'name' => 'ProductName', 'comment' => 'best product comment 3'],
['id' => 3, 'name' => 'ProductName2', 'comment' => 'best product comment 4'],
['id' => 3, 'name' => 'ProductName2', 'comment' => 'best product comment 5']
];
$output_array = array_values(array_reduce($input_array, function($output_array, $item) {
if (array_key_exists($item['id'], $output_array)) {
$output_array[$item['id']]['comment'][] = $item['comment'];
}
else {
$item['comment'] = (array)$item['comment'];
$output_array[$item['id']] = $item;
}
return $output_array;
}, []));
echo '<pre>'; var_dump($output_array); echo '</pre>';
答案 1 :(得分:0)
我不确定这是否是您要讨论的内容,但这是将商品评论归为一组的方法。
$inputarray = array(
array("id" => 2,"name" => "ProductName","comment" => "best product comment 1"),
array("id" => 2,"name" => "ProductName","comment" => "best product comment 2"),
array("id" => 2,"name" => "ProductName","comment" => "best product comment 3")
);
$outputarray = [];
$tmp_comments = [];
foreach ($inputarray as $arrays) {
$tmp_comments[$arrays['id']][] = $arrays['comment'];
$outputarray[$arrays['id']] = array('id' => $arrays['id'], 'name' => $arrays['name']);
}
foreach ($tmp_comments as $id => $comments) {
$outputarray[$id]['comment'] = $comments;
}
print_r($outputarray);
输出
Array
(
[2] => Array
(
[id] => 2
[name] => ProductName
[comment] => Array
(
[0] => best product comment 1
[1] => best product comment 2
[2] => best product comment 3
)
)
)