-1

嗨我有一个数组的输出如下:

Array ( 
[0] => 66, 65, 64 
[1] => 57 
[2] => 66,23 
[3] => 66
) 

如何删除重复值并将集合转换为逗号分隔的字符串?唯一的输出是66,65,64,57,23。谢谢

4

5 回答 5

2

使用array_unique()array_reverse()

$array = Array ( 
  0 => '66, 65, 64',
  1 => '57', 
  2 => '66,23',
  3 => '66',
);
$collection = array();
foreach($array as $numbers) {
  $nums = explode(',', $numbers);
  foreach($nums as $num) {
    $collection[] = trim($num);
  }
}
// unique and sort
$collection = array_unique($collection, SORT_NUMERIC);
// reverse it so that it can be descending order
$collection = array_reverse($collection);
print_r($collection);

这将输出:

Array (
  [0] => 66
  [1] => 65
  [2] => 64
  [3] => 57
  [4] => 23
)
于 2013-08-07T06:11:22.043 回答
1

您遍历数组并通过检查其值将其添加到最终数组中,然后implode构造一个字符串。

$array = Array ( 
0 => array(66, 65, 64), 
1 => array(57), 
2 => array(66,23), 
3 => array( 66)
); 

$final = array();

foreach ($array as $item) {
   foreach ($item as $num) {
       if (!in_array($num, $final)) $final[] = $num;
   }
}

$str = implode(",", $final);
echo $str
于 2013-08-07T06:01:15.450 回答
0

好吧,代码很丑...

$test = [
 '0' => '66, 65',
 '1' => '80', '66'
];
$temp = implode(',', array_map('trim', array_unique(explode(',', implode(',', $test)))));
print_r($test);
print_r($temp);

//输出

 Array (
  [0] => 66, 65
  [1] => 80
  [2] => 66 
  ) 

 66,65,80
于 2013-08-07T06:08:04.713 回答
0

好的:

<?php

$array = array( 
     "66, 65, 64", 
     57, 
     "66,23", 
     66
);

function dosplit($a,$b) {
    if (preg_match("/,/",$b)) {
        $a = array_merge($a, preg_split('/\s*,\s*/', $b));
    } else {
        array_push($a, $b);
    }
    return $a;
}
$result = array_reduce($array, 'dosplit' ,array());
$array = array_unique($result);

输出是:

Array
(   
    [0] => 66
    [1] => 65
    [2] => 64
    [3] => 57
    [5] => 23
)
于 2013-08-07T06:12:36.897 回答
0

这可能对您有用:

$array = array(
    "66, 65, 64 ",
    "57",
    "66,23",
    "66",
);
echo "<pre>";
print_r($array);
//to make single line
foreach ($array as $val) {
    $singleline.=$val . ",";
}
echo $singleline . "</br>";
//remove the "," end of the value
$endvlaue = rtrim($singleline, ",");
echo $endvlaue;
//make an array
$val = explode(",", $endvlaue);
echo "<pre>";
print_r($val);
echo "<pre>";
//make uniqu
$finalvalue = array_unique($val);
echo "<pre>";
//make , seperator
print_r(implode(",", $finalvalue));
于 2013-08-07T06:44:44.743 回答