【问题标题】:Delete array items if repeats more then once, Php [duplicate]如果重复不止一次,则删除数组项,Php [重复]
【发布时间】:2019-06-02 20:04:34
【问题描述】:

我有一个数组,它有重复的项目。因此,如果重复,我会尝试删除项目。例如:

$链接:

  string(35) "/mjr/semba-tower/outline/index.html"
  [1]=>
  string(38) "/mjr/mc-futsukaichi/outline/index.html"
  [2]=>
  string(31) "/mjr/chihaya/outline/index.html"
  [3]=>
  string(35) "/mjr/semba-tower/outline/index.html"

正如您在阵列中看到的 2 个 semba 塔,我想删除其中一个 if。 我试过了,但输出返回 0 项。

$output = [];
        foreach(array_count_values($links) as $value => $count)
        {
            if($count == 1)
            {
                $output[] = $value;
            }
        }

        var_dump($output); 

还有其他方法可以解决这个问题吗?

【问题讨论】:

  • 您可以使用 array_unique 删除重复项。例如:array_unique($links)
  • 哦,这很容易解决问题。 @CCoder 非常感谢。
  • @CCoder 虽然这很简单,但您仍然应该发布答案,而不是评论。
  • 哦,好吧@尼克。由于帖子已经回复,将在下一个帖子中跟进。

标签: php


【解决方案1】:

Use the PHP array_unique() function

您可以使用 PHP array_unique() 函数来删除重复元素或数组中的值。如果数组包含字符串键,则此函数将保留每个值遇到的第一个键,并忽略所有后续键。

$links = array(
    "/mjr/semba-tower/outline/index.html",
    "/mjr/mc-futsukaichi/outline/index.html",
    "/mjr/chihaya/outline/index.html",
    "/mjr/semba-tower/outline/index.html"
);

// Deleting the duplicate items
$result = array_unique($links);
print_r($result);

输出:

Array ( [0] => /mjr/semba-tower/outline/index.html [1] => /mjr/mc-futsukaichi/outline/index.html [2] => /mjr/chihaya/outline/index.html )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    相关资源
    最近更新 更多