How to remove duplicate values from an associative array based on a specific value?

前端 未结 5 938
再見小時候
再見小時候 2020-12-20 01:37

I have an array that looks just like that:

array(3) { [\"fk_article_id\"]=> string(1) \"4\" [\"first_name\"]=> string(6) \"Ulrike\" [\"last_name\"]=>         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-20 02:12

    A quick way using array_reduce would look like:

    $unique = array_reduce($subject, function($final, $article){
        static $seen = array();
        if ( ! array_key_exists($article['fk_article_id'], $seen)) {
            $seen[$article['fk_article_id']] = NULL;
            $final[] = $article;
        }
        return $final;
    });
    

    Try a working example.


    Edit: Seems you don't want to work with the aggregated results. Here are two other thoughts:

    Filtering in PHP

    $seen = array();
    while ($row = pg_fetch_assoc($authors_result)) {
        // Skip this row if we have already seen its article id
        if (array_key_exists($row['fk_article_id'], $seen)) {
            continue;
        }
        // Note that we have seen this article
        $seen[$row['fk_article_id']] = NULL;
        // Do whatever with your row
        var_dump($row);
    }
    

    Filtering in the DB

    The idea here is to change the query being executed so that the repeated article ids do not appear in the result set. How this is done will depend on the query that you're already using.

提交回复
热议问题