in_array和array_unique不起作用

时间:2016-03-21 11:45:35

标签: php unique-array

即使尝试了in_arrayarray_unique这两项功能,我的代码仍然会显示重复的值。我从数据库中获取值。有些行有多个值。 我想用逗号来分解它们,而不是删除重复项。 请提前帮助,谢谢。

<?php while ($row = mysql_fetch_array($sql)) {
   $mark=explode(',', $row['sku']);
   foreach($mark as $out) {
     if(!in_array($out, $array)){
     $array[] = $out;
     }
   }

}
$unique_array = array_unique($array, SORT_REGULAR);
natsort($unique_array);
print_r($unique_array);
?>

1 个答案:

答案 0 :(得分:0)

以下是一个示例代码,可以执行您想要的操作:http://sandbox.onlinephpfunctions.com/code/4895a5b39c555835e378114eabc7ed78c6811285

<?php

// I create some sample data
$rows = [['sku' => 'a,b,c'], ['sku' => 'c,d,e'], ['sku' => 'e,f,g']];

$array = [];

// You want to replace this with your while loop
foreach ($rows as $row) {
    $mark = explode(',', $row['sku']);

    foreach ($mark as $out) {
        if (!in_array($out, $array)) {
            array_push($array, $out);
        }
    }

}

// I don't think you need this here, because you already ensure that the array won't contain duplicates
$unique_array = array_unique($array, SORT_REGULAR);

natsort($unique_array);
var_dump($unique_array);
var_dump($array);

所以使用你的while ($row = mysql_fetch_array($sql))应该是这样的:

<?php

$array = [];
while ($row = mysql_fetch_array($sql)) {
    $mark = explode(',', $row['sku']);

    foreach ($mark as $out) {
        if (!in_array($out, $array)) {
            array_push($array, $out);
        }
    }

}

natsort($unique_array);
var_dump($unique_array);