【问题标题】:array_unique not working as expected in phparray_unique 在 php 中没有按预期工作
【发布时间】:2012-05-11 12:05:51
【问题描述】:

这是一个问题。 我正在按数组中的换行符分解字符列表。并在其上做唯一的数组。但它没有按预期工作。 下面是代码:

$list = "test
ok
test
test
ok
ok
test";
$list_explode = explode("\n", $list); //exploding the characters of the list from the input
//displaying unique 

array_map('trim', $list_explode);
$result = array_unique($list_explode);
print_r($result);

结果是

Array ( [0] => test [1] => ok [6] => test )

【问题讨论】:

  • 使用var_dump 而不是print_r。它会告诉你字符串不同。

标签: php array-unique


【解决方案1】:

使用var_dump 而不是print_r,您会发现“测试” (take a look at codepad) 之间存在差异。

您的代码包含\r\n 作为换行符,并且您在\n 处拆分,因此除了最后一个之外,所有条目中仍然存在\r

您已经使用array_map 来防止这种情况,但忘记在后面的代码中使用retun-value(它不能通过引用工作)。将该行更改为:

$list_explode = array_map('trim', $list_explode);

执行此操作后,您将得到您所期望的 (see at codepad again)。

【讨论】:

    【解决方案2】:

    您没有考虑到您的字符串有一个\r\n 序列作为换行符。在爆炸过程中,您只删除了 \n 部分,因此您的结果实际上是这样的:

    Array ( [0] => test\r [1] => ok [6] => test )
    

    但是,\r 不会打印为可见字符(即使代码看到它)。

    【讨论】:

      【解决方案3】:

      您可以通过两种主要方式拆分多行文本:

      1. 使用$list_explode = array_map('rtrim', explode("\n", $list));

      2. 使用$list_explode = preg_split("/\r?\n/", $list);

      【讨论】:

        猜你喜欢
        • 2014-03-12
        • 2016-08-29
        • 2012-01-16
        • 2011-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多