2017-09-15 130 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 
     ) 

)