简体   繁体   English

根据另一个数组中的唯一值获取数组?

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

I have an array of arrays. 我有一个数组数组。 One of the fields within in the inner array needs to be unique so that when I show the results it only displays unique entries. 内部数组中的字段之一必须是唯一的,以便当我显示结果时,它仅显示唯一的条目。

array_unique is available but it looks like that only works on single dimension arrays. array_unique可用,但看起来仅适用于一维数组。 I could probably do a comparison operation on while iterating through the array but that seems like the least efficient way to do it. 我可能在遍历数组时可以进行比较操作,但这似乎是最不高效的方法。

The way the data is stored in the database(not my design) is tricky and I wont be able to just pull in the distinct results using sql. 数据存储在数据库中的方式(不是我的设计)很棘手,我将无法仅使用sql提取不同的结果。

Any ideas? 有任何想法吗?

You could easily use a combination of array_unique and array_column 您可以轻松使用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);

and then filter in which ever way you see fit 然后以您认为合适的方式进行过滤

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

EDIT : the filter doesn't actually work now that I think of it, below is a slightly different approach: 编辑 :我想到它之后,该过滤器实际上不起作用,下面是一种稍微不同的方法:

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