2017-09-15 34 views
-1

我有一个从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"] = 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; 


... 
.... 

我想要做的是循环这个$行数组并获取最近的id值。

例如,在上面的例子我想回的是:

id value 
18 100 
5  20 
3  20 

我怎样才能做到这什么逻辑?

+0

所以...如果你想循环...循环在哪里? – Dekel

+0

你试过了吗? – Emaro

+0

你提到5的第一个记录是20,但在你的回报值中,你放40。为什么? –

回答

1

它可以通过多种方式来完成。最简单的一个方法是使用一个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 
) 

相同的处理,但使用array_reduce()

$result = array_reduce(
    $row, 
    function(array $c, array $i) { 
     if (! array_key_exists($i['id'], $c)) { 
      $c[$i['id']] = $i['value']; 
     } 
     return $c; 
    }, 
    array() 
); 
0

array_unique()函数正是你所看到的。 在这里看到的文档:array_unique() documentation

+1

您链接到法国网站。英文一个在这里:http://php.net/manual/en/function。array-unique.php – Emaro

+1

哎呀,我什至没有注意,我已经修复了链接,谢谢:) –

1

试试这个

$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 
     ) 

) 
0

使用array_column与索引键几乎做到这一点,但它会以相反的顺序,那么您可以反转输入以使其起作用。

$result = array_column(array_reverse($row), 'value', 'id'); 
1

如果你想只保留每个“身份证”的第一次出现,然后只需添加值合计阵列 - 但只有当他们没有已经添加。然后获取聚合数组的值。

https://tehplayground.com/NRvw9uJF615oeh6C - 按Ctrl + Enter运行


$results = array(); 
foreach ($row as $r) { 
    $id = $r['id']; 
    if (! array_key_exists($id, $results)) { 
     $results[$id] = $r; 
    } 
} 

$results = array_values($results); 
print_r($results); 

Array 
(
    [0] => Array 
     (
      [id] => 18 
      [value] => 100 
     ) 

    [1] => Array 
     (
      [id] => 5 
      [value] => 20 
     ) 

    [2] => Array 
     (
      [id] => 3 
      [value] => 20 
     ) 

)