PHP试题
判断一个数组里有没有重复的值
if (count($array) != count(array_unique($array))) {
echo '该数组有重复值';
}
统计出两个数组(长度10000)中同时出现过的,并且总出现次数最多的单词
$arr1 = array(1, "hello", 1, "world", "hello",2,2);
$arr2 = array(1, "hello", 11, "world1", "hello1",2,2);
$arr_count1=array_count_values($arr1);
$arr_count2=array_count_values($arr2);
$arr=array_intersect($arr1,$arr2);
$arr_result=array();
foreach ($arr as $v){
$arr_result[$v]=$arr_count1[$v]+$arr_count2[$v];
}
asort($arr_result);
var_dump($arr_result);
找出数组中不重复出现的值
$all = '1,2,3,4,5,6';
$in = '2,3,4';
$str = $all.','.$in;
$arr = explode(',', $str);
// 计算数组中每个值出现的次数
$arr = array_count_values($arr);
foreach ($arr as $key => $value) {
if($value == 1){
$left[] = $key;
}
}
print_r($left);
array_search与array_column实现二维数组查找
$userdb = array(
0 => array(
'uid' => 100,
'name' => 'Sandra Shush',
'url' => 'urlof100'
),
1 => array(
'uid' => 5465,
'name' => 'Stefanie Mcmohn',
'pic_square' => 'urlof100'
),
2 => Array(
'uid' => 40489,
'name' => 'Michael',
'pic_square' => 'urlof40489'
)
);
$found_key = array_search(40489, array_column($userdb, 'uid'));
/**
如果$userdb很大,建议使用一个变量,避免搜索每个元素时都调用array_column()
$uid = array_column($userdb, 'uid');
$found_key = array_search(40489, $uid);
*/
var_dump($found_key);