Php 循环遍历数组并获取非重复值
我有一个从mongoDB查询的元素数组 此数组具有设备id和设备消耗值 例如,有3个不同的ID->18,5,3和多个混合值Php 循环遍历数组并获取非重复值,php,Php,我有一个从mongoDB查询的元素数组 此数组具有设备id和设备消耗值 例如,有3个不同的ID->18,5,3和多个混合值 // first record of 18 so get value. $row[0]["id"] = 18; $row[0]["value"] = 100; // not first record of 18 so ignore and move to the next record $row[1]["id"] = 18; $row[1]["value"]
// first record of 18 so get value.
$row[0]["id"] = 18;
$row[0]["value"] = 100;
// not first record of 18 so ignore and move to the next record
$row[1]["id"] = 18;
$row[1]["value"] = 40;
// first record of 5 so get value.
$row[2]["id"] = 5;
$row[2]["value"] = 20;
// not first record of 18 so ignore and move to the next record
$row[3]["id"] = 18;
$row[3]["value"] = 30;
// first record of 3 so get value.
$row[4]["id"] = 3;
$row[4]["value"] = 20;
//not first record of 5 so ignore and move to the next record**
$row[5]["id"] = 5;
$row[5]["value"] = 30;
// not first record of 18 so ignore and move to the next record
$row[6]["id"] = 18;
$row[6]["value"] = 10;
...
....
我试图做的是循环遍历这个$row数组,并获取id的最新值
例如,在上面的示例中,我想要返回的是:
id value
18 100
5 20
3 20
我怎样才能实现这种逻辑呢?数组的unique()函数正是您所看到的。
请参阅此处的文档:试试这个
$alreadyfound = []; // empty array
$result = [];
foreach ($row as $item)
{
if (in_array($item["id"], $alreadyfound))
continue;
$alreadyfound[] = $item["id"]; // add to array
$result[] = $item;
}
结果
Array
(
[0] => Array
(
[id] => 18
[value] => 100
)
[1] => Array
(
[id] => 5
[value] => 20
)
[2] => Array
(
[id] => 3
[value] => 20
)
)
使用带有索引键的
array\u column
几乎可以做到这一点,但顺序相反,因此您可以反转输入以使其正常工作
$result = array_column(array_reverse($row), 'value', 'id');
如果只想保留每个“id”的第一个匹配项,那么只需将这些值添加到聚合数组中,但前提是这些值尚未添加。然后获取聚合数组的值 -按Ctrl+Enter以运行
这可以通过几种方式实现。最简单的方法是使用
foreach
:
$result = array();
foreach ($row as $i) {
if (! array_key_exists($i['id'], $result)) {
$result[$i['id']] = $i['value'];
}
}
# Verify the result
print_r($result);
输出为:
Array
(
[18] => 100
[5] => 20
[3] => 20
)
相同的处理,但使用:
所以如果您正在尝试循环。。。循环在哪里?你试过了吗?你提到5的第一个记录是20,但在你的返回值中你把40。为什么?t不是最近的,它是最高的。从数据库中检索它们比在php中过滤要高效得多:@AlexBlex我没有得到最高的…你可以链接到法国网站。英文的在这里:哎呀,我都没注意,我已经修复了链接,谢谢:)
$result = array();
foreach ($row as $i) {
if (! array_key_exists($i['id'], $result)) {
$result[$i['id']] = $i['value'];
}
}
# Verify the result
print_r($result);
Array
(
[18] => 100
[5] => 20
[3] => 20
)
$result = array_reduce(
$row,
function(array $c, array $i) {
if (! array_key_exists($i['id'], $c)) {
$c[$i['id']] = $i['value'];
}
return $c;
},
array()
);