我的代码仍然显示重复的值,即使在尝试了in_array
和array_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);
?>
下面是一个示例代码,它应该做你想要的: 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);