[英]Get Unique Value from array in Php
我需要從array獲取唯一值,輸入是
$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合並所有值,並且避免重復。
請先使用array_mearge然后再使用array_unique
<?php
$newArray = array_merge($chairs_can_pullfrom[0], $chairs_can_pullfrom[1], $chairs_can_pullfrom[2]);
$result = array_unique($newArray);
?>
假設$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;
});
這是我的測試代碼。
<?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);
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.