Php Array删除重复和字符串转换

时间:2013-08-07 05:55:11

标签: php

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

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

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

5 个答案:

答案 0 :(得分: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
)

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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
)

答案 4 :(得分: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));