如何从数组中只获取唯一值?

时间:2017-10-11 14:25:14

标签: php arrays foreach

我正在尝试计算数组中的所有多个值并显示在一个数组中。

Array
(
[0] => unicomp6.unicomp.net 
[1] => 
[2] => burger.letters.com 
[3] => 
[4] => burger.letters.com 
[5] => 
[6] => burger.letters.com 
[7] => 
[8] => 
[9] => d104.aa.net 
[10] => 
[11] => unicomp6.unicomp.net 
[12] => 
[13] => 
[14] => unicomp6.unicomp.net 
[15] => 
[16] => unicomp6.unicomp.net 
[17] => 
[18] => d104.aa.net 
[19] => 
[20] => d104.aa.net 
[21] => 
)

输出结果就是这样。

 Array
 (
 [unicomp6.unicomp.net ] => 4
 [burger.letters.com ] => 3
 [d104.aa.net] => 3
)

我已编写此代码,但我想知道如何合并数组中的所有唯一值,请帮助我iphp如何做到:

$j=0;
 $arrayName = array();
 foreach ($host_name as $key => $value) {

    $size= sizeof($host_name);

   if($value!='')
   {       
    $count=1;
    for ($k=0; $k<$size; $k++) { 

        if($host_name[$j]==$host_name[$k])
        {

            $arrayName = array($host_name[$j]=> $count++);
        }
    }
 }   
         $j++;
 }
    print_r($arrayName);

1 个答案:

答案 0 :(得分:1)

    <?php

    $data=Array
    (
       'unicomp6.unicomp.net','','burger.letters.com','','burger.letters.com','','burger.letters.com','','','d104.aa.net','unicomp6.unicomp.net','','unicomp6.unicomp.net','d104.aa.net','','d104.aa.net',''
    );
  echo"<pre>";
print_r(array_count_values(array_filter($data)));
echo"</pre>";

修剪空字段后的输出:

Array
(
    [unicomp6.unicomp.net] => 3
    [burger.letters.com] => 3
    [d104.aa.net] => 3
)
相关问题