Codeigniter:如何从索引名称指定的数组中删除重复元素

时间:2017-04-28 12:36:02

标签: php arrays codeigniter duplicates

如何通过指定article_id之类的索引来删除Duplicate Array元素 这意味着数组中没有其他元素具有相同的文章ID。

这就是我得到的

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

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

输出:

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
        )

)

1 个答案:

答案 0 :(得分: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;
}

资料来源: [https://stackoverflow.com/a/6461034/7891160][1]