【问题标题】:Get array based on unique values within another array?根据另一个数组中的唯一值获取数组?
【发布时间】:2016-06-13 14:30:53
【问题描述】:

我有一个数组数组。内部数组中的一个字段必须是唯一的,这样当我显示结果时它只会显示唯一的条目。

array_unique 是可用的,但它看起来只适用于一维数组。我可能可以在遍历数组时进行比较操作,但这似乎是效率最低的方法。

数据存储在数据库中的方式(不是我的设计)很棘手,我不能只使用 sql 提取不同的结果。

有什么想法吗?

【问题讨论】:

  • 至少给出一个数据结构的简短例子。
  • foreach ($items as $item) $unique[$item['theUniqueField']] = $item;

标签: php arrays sorting


【解决方案1】:

您可以轻松使用array_unique 和array_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;
} );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 2018-06-18
    • 1970-01-01
    相关资源
    最近更新 更多