【问题标题】:Codeigniter : How to remove duplicate element from array specified by index nameCodeigniter:如何从索引名称指定的数组中删除重复元素
【发布时间】:2017-09-26 14:03:26
【问题描述】:

如何通过指定像 article_id 这样的索引来删除重复的数组元素 这意味着在 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
        )

)

【问题讨论】:

  • 提示:array_unique()(实例上可能有问题)或简单的foreach 并创建一个索引为 id 的新数组。
  • 最好的方法是您需要从 MYSQL 查询本身中删除重复记录。您可以使用“DISTINCT”关键字作为文章 ID。这样您就永远不会从数据库中获得重复的记录。对于 ex SELECT DISTINCT(article_id) from table_name where keyword LIKE %copy%
  • 只需在您的查询中添加SELECT DISTINCT(article_id)...
  • 使用$this-&gt;group_by('article_id')$this-&gt;db-&gt;distinct();$this-&gt;db-&gt;select('DISTINCT(article_id)');

标签: php arrays codeigniter duplicates


【解决方案1】:
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]

【讨论】:

    猜你喜欢
    • 2012-02-12
    • 2021-12-31
    • 2021-04-20
    • 2014-03-18
    • 1970-01-01
    • 2019-01-18
    • 2012-08-26
    • 1970-01-01
    相关资源
    最近更新 更多