簡體   English   中英

根據另一個數組中的唯一值獲取數組?

[英]Get array based on unique values within another array?

我有一個數組數組。 內部數組中的字段之一必須是唯一的,以便當我顯示結果時,它僅顯示唯一的條目。

array_unique可用,但看起來僅適用於一維數組。 我可能在遍歷數組時可以進行比較操作,但這似乎是最不高效的方法。

數據存儲在數據庫中的方式(不是我的設計)很棘手,我將無法僅使用sql提取不同的結果。

有任何想法嗎?

您可以輕松使用array_uniquearray_column的組合

$records = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    )
);

$ids = array_column($records, 'id');
$unique_ids = array_unique($ids);

然后以您認為合適的方式進行過濾

array_filter($records, function($row) use ($unique_ids) {
    return in_array($row['id'], $unique_ids);
} );

編輯 :我想到它之后,該過濾器實際上不起作用,下面是一種稍微不同的方法:

array_filter($records, function($row) use ($unique_ids) {
    $array_pos = array_search($row['id'], $unique_ids, true);
    if($array_pos !== false) {
        //need to remove it once used or it wont be unique
        unset($unique_ids[$array_pos]);
    }
    return $array_pos !== false;
} );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM