Skip to content
Advertisement

Codeigniter : How to remove duplicate element from array specified by index name

How to remove Duplicate Array element by specifying index like article_id That means there would no other element having same article id in array .

This is what i am getting

$data["related_post"]   =$CI->Article_model->get_related_post($SearchTag);

and

echo "<pre>";
 print_r($data["related_post"]);
echo "</pre>";

Output:

Array
(
    [0] => stdClass Object
        (
            [article_id] => 49
            [article_viewed] => 156
            [article_title] => Copy 1 column to another by mysql query
            [article_url] => copy-1-column-to-another-by-mysql-query
            [article_status] => active
            [tag_name] => mysql
        )

    [1] => stdClass Object
        (
            [article_id] => 49
            [article_viewed] => 156
            [article_title] => Copy 1 column to another by mysql query
            [article_url] => copy-1-column-to-another-by-mysql-query
            [article_status] => active
            [tag_name] =>  sql
        )

    [2] => stdClass Object
        (
            [article_id] => 49
            [article_viewed] => 156
            [article_title] => Copy 1 column to another by mysql query
            [article_url] => copy-1-column-to-another-by-mysql-query
            [article_status] => active
            [tag_name] =>  unique-key
        )

)

Advertisement

Answer

function get_keys_for_duplicate_values($my_arr, $clean = false) {
    if ($clean) {
        return array_unique($my_arr);
    }

    $dups = $new_arr = array();
    foreach ($my_arr as $key => $val) {
      if (!isset($new_arr[$val])) {
         $new_arr[$val] = $key;
      } else {
        if (isset($dups[$val])) {
           $dups[$val][] = $key;
        } else {
           $dups[$val] = array($key);
           // Comment out the previous line, and uncomment the following line to
           // include the initial key in the dups array.
           // $dups[$val] = array($new_arr[$val], $key);
        }
      }
    }
    return $dups;
}

Source : [https://stackoverflow.com/a/6461034/7891160][1]

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement