在这里,我想找到unique
值,所以我正在编写这样的代码,但我无法得到答案,因为我不想要数组格式。我只想要字符串
<?php
$array = array("kani","yuvi","raja","kani","mahi","yuvi") ;
$unique_array = array(); // unique array
$duplicate_array = array(); // duplicate array
foreach ($array as $key=>$value){
if(!in_array($value,$unique_array)){
$unique_array[$key] = $value;
}else{
$duplicate_array[$key] = $value;
}
}
echo "unique values are:-<br/>";
echo "<pre/>";print_r($unique_array);
echo "duplicate values are:-<br/>";
echo "<pre/>";print_r($duplicate_array);
?>
&#13;
答案 0 :(得分:0)
要从数组中获取唯一值,请使用array_unique()
:
$array = array(1,2,1,5,10,5,10,7,9,1) ;
array_unique($array);
print_r(array_unique($array));
输出:
Array
(
[0] => 1
[1] => 2
[3] => 5
[4] => 10
[7] => 7
[8] => 9
)
要在数组中使用array_count_values()
获取重复值:
$array = array(1,2,1,5,10,5,10,7,9,1) ;
print_r(array_count_values($array));
输出:
Array
(
[1] => 3 // 1 is duplicated value as it occurrence is 3 times
[2] => 1
[5] => 2 // 5 is duplicated value as it occurrence is 3 times
[10] => 2 // 10 is duplicated value as it occurrence is 3 times
[7] => 1
[9] => 1
)
答案 1 :(得分:0)
您可以在单行中使用array_unique()
,如下所示: -
<?php
$unique_array = array_unique($array); // get unique value from initial array
echo "<pre/>";print_r($unique_array); // print unique values array
?>
输出: - https://eval.in/601260
参考: - http://php.net/manual/en/function.array-unique.php
如果您想要字符串格式: -
echo implode(',',$final_array);
输出: - https://eval.in/601261
你想要的方式是: -
OR
答案 2 :(得分:0)
<?php
$arr1 = [1,1,2,3,4,5,6,3,1,3,5,3,20];
print_r(arr_unique($arr1)); // will print unique values
echo "<br>";
arr_count_val($arr1); // will print array with duplicate values
function arr_unique($arr) {
sort($arr);
$curr = $arr[0];
$uni_arr[] = $arr[0];
for($i=0; $i<count($arr);$i++){
if($curr != $arr[$i]) {
$uni_arr[] = $arr[$i];
$curr = $arr[$i];
}
}
return $uni_arr;
}
function arr_count_val($arr) {
$uni_array = arr_unique($arr1);
$count = 0;
foreach($uni_array as $n1) {
foreach($arr as $n1) {
if($n1 == $n2) {
$count++;
}
}
echo "$n1"." => "."$count"."<br>";
$count=0;
}
}
?>
答案 3 :(得分:-1)
我为您选择的接受答案感到困惑-我无法想象它可能如何满足您的要求。
array_count_values()
自PHP4开始可用,所以这是值得一提的英雄。
代码:(Demo)
$array = array("kani","yuvi","raja","kani","mahi","yuvi") ;
$counts = array_count_values($array); // since php4
foreach ($counts as $value => $count) {
if ($count == 1) {
$uniques[] = $value;
} else {
$duplicates[] = $value;
}
}
echo "unique values: " , implode(", ", $uniques) , "\n";
echo "duplicate values: " , implode(", ", $duplicates);
输出:
unique values: raja, mahi
duplicate values: kani, yuvi