0

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
        )

)
4
  • Tip: array_unique() (maybe buggy on instances) or an simple foreach and create an new array where the index is the id. Commented Apr 28, 2017 at 12:38
  • Best way is you need to remove the duplicate records from the MYSQL query itself. You can use "DISTINCT" keyword for the article ID. So that you never get the duplicate records from DB. For ex SELECT DISTINCT(article_id) from table_name where keyword LIKE %copy% Commented Apr 28, 2017 at 12:42
  • 2
    JUST add SELECT DISTINCT(article_id)... in your query Commented Apr 28, 2017 at 12:44
  • Use $this->group_by('article_id') or $this->db->distinct(); or $this->db->select('DISTINCT(article_id)'); Commented Apr 28, 2017 at 18:06

1 Answer 1

0
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]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.