从Php中的数组中获取唯一值

时间:2014-05-08 17:39:00

标签: php arrays

我需要从数组中获取唯一值,输入是

$item = $_GET['table_id'];              

$table_id = explode(",",$item);             
$table_count = count($table_id);            

for($i=0 ; $i<$table_count; ++$i)             
    {
        $qry6 = mysql_query("SELECT * FROM chairpulling_info WHERE table_id = '$table_id[$i]'");
        $row6 = mysql_fetch_array($qry6);
        $chairs_can_pullfrom[$i] = $row6['chairs_can_pullfrom'];        
    }

所以现在输入将是这样的

$chairs_can_pullfrom[0] = 1,2 ;
$chairs_can_pullfrom[1] = 3,2,5;
$chairs_can_pullfrom[2] = 1,2,3;

我正在寻找的最终输出是

$result = 5 
$result_2 = 1,2,3,5

$ result是唯一值,$ result_2合并所有值,避免重复。

3 个答案:

答案 0 :(得分:0)

请使用array_mearge然后使用array_unique

<?php 

$newArray = array_merge($chairs_can_pullfrom[0], $chairs_can_pullfrom[1], $chairs_can_pullfrom[2]);

$result =  array_unique($newArray);

?>

答案 1 :(得分:0)

假设$chairs_can_pullfrom[0]$chairs_can_pullfrom[1]$chairs_can_pullfrom[2]是数组:

$allvalues     = array_merge($chairs_can_pullfrom[0], $chairs_can_pullfrom[1], $chairs_can_pullfrom[2]);
$unique_values = array_unique($allvalues);
$count_values  = array_count_values($allvalues);
$unique        = array_filter($allvalues, function($var) use ($count_values){
    return $count_values[$var] === 1;
});

Demo

答案 2 :(得分:0)

这是我的测试代码。

<?php
$chairs_can_pullfrom[0] = array(1, 2);
$chairs_can_pullfrom[1] = array(3,2,5);
$chairs_can_pullfrom[2] = array(1,2,3);

$tmp = array();

$result = array();
$result_2 = array();

foreach($chairs_can_pullfrom as $chairs){
    foreach($chairs as $chair){
        if(!array_key_exists($chair, $tmp)){
            $tmp[$chair] = 1;
        }
        else {
            $tmp[$chair]++;
        }
    }
}

foreach($tmp as $key => $value){
    if($value == 1){
        $result[] = $key;
    }
    $result_2[] = $key;
}

var_dump($result, $result_2);
?>