在Php中从数组中获取唯一值
我需要从数组中获取唯一的值,输入是在Php中从数组中获取唯一值,php,arrays,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
$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'];
}
我想要的最终输出是
$result = 5
$result_2 = 1,2,3,5
$result是唯一值,$result\u 2合并所有值并避免重复。请使用array\u mearge,然后使用array\u unique
<?php
$newArray = array_merge($chairs_can_pullfrom[0], $chairs_can_pullfrom[1], $chairs_can_pullfrom[2]);
$result = array_unique($newArray);
?>
假设
$chairs\u can\u pullfrom[0]
,$chairs\u can\u pullfrom[1]
,$chairs\u can\u 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;
});
这是我的测试代码
<?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);
?>
为什么$result
为5?我认为如果它是唯一值的数目,它应该是4。@MinhNguyen在这个输入中,1,2,3在另一个输入中重复,但5没有重复,所以我需要将它存储在另一个变量中/
<?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);
?>