如何从PHP中删除多维数组中的重复值?
示例数组:
Array
(
[choice] => Array
(
[0] => Array
(
[day] => Monday
[value] => Array
(
[0] => Array
(
[name] => BI
[time] => 10:00
[location] => B123
)
[1] => Array
(
[name] => BI
[time] => 11:00
[location] => A123
)
)
)
[1] => Array
(
[day] => Tuesday
[value] => Array
(
[0] => Array
(
[name] => BI
[time] => 10:00
[location] => B123
)
[1] => Array
(
[name] => BI
[time] => 11:00
[location] => A123
)
)
)
)
)
我想删除重复name
的内容。所以我只想每天保留一个主题。
到目前为止我的代码:
$taken = array();
foreach($subject_list['choice'][0]["value"] as $key =>$item )
{
if(!in_array($item['name'], $taken))
{
$taken[] = $item['name'];
}else
{
unset($flight_list['choice'][0]["value"][$key]);
}
}
上面代码的输出(显然是错误的):
Array
(
[choice] => Array
(
[0] => Array
(
[day] => Monday
[value] => Array
(
[0] => Array
(
[name] => BI
[time] => 10:00
[location] => B123
)
)
)
[1] => Array
(
[day] => Tuesday
[value] => Array
(
[0] => Array
(
[name] => BI
[time] => 10:00
[location] => B123
)
[1] => Array
(
[name] => BI
[time] => 11:00
[location] => A123
)
)
)
)
)
任何人都可以帮助我如何在name
删除相同的课程Tuesday
。
答案 0 :(得分:3)
如果您希望在value
每个name
批次中保留第一组唯一值,则只需为此创建一个临时容器。如果您已将其推送,则在收集后不要处理任何内容,请使用foreach
&
引用覆盖批处理:
foreach($subject_list['choice'] as &$items) {
$temp = array(); // temporary container for current iteration
foreach($items['value'] as $value) {
if(!isset($temp[$value['name']])) { // if its new
$temp[$value['name']] = $value; // push the batch using the key name
}
}
$items['value'] = $temp; // apply unique value in the end of this batch
}
答案 1 :(得分:0)
其中$array
是你的数组即将到来的php变量
$array = array_map("unserialize", array_unique(array_map("serialize", $array)));
答案 2 :(得分:-2)
快速谷歌删除多维数组中的重复项:
<?php
function super_unique($array)
{
$result = array_map("unserialize", array_unique(array_map("serialize", $array)));
foreach ($result as $key => $value)
{
if ( is_array($value) )
{
$result[$key] = super_unique($value);
}
}
return $result;
}
?>