以下是否有功能性的方法?
我想使用array_filter,但我想不出一种在array_filter回调中构建$ ids_used数组的方法。
$data = [
[
'id' => 1,
'price' => 5,
],
[
'id' => 1,
'price' => 6,
]
];
$ids_used = [];
foreach($data as $index => $item)
{
if(in_array($item['id'], $ids_used)) {
unset($data[$index]);
}
else
{
$ids_used[] = $item['id'];
}
}
// expected output is: $data = [['id' => 1,'price' => 5]];
答案 0 :(得分:2)
如果您只想将其包装在array_filter中:
<?php
$data = [
[
'id' => 1,
'price' => 5,
],
[
'id' => 1,
'price' => 6,
]
];
$ids_used = [];
$filtered = array_filter($data, function($item) use (&$ids_used) {
if(!in_array($item['id'], $ids_used)) {
$ids_used[] = $item['id'];
return true;
} else {
return false;
}
});
var_dump($ids_used);
var_dump($filtered);
?>
答案 1 :(得分:1)