php - in_array()
本文介绍了php - in_array()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
//现有的ID集合$set['old_id']与前台传来的id集合$set['new_id']作对比,
public function contrast_new_old_id(){
//从前台传来的id组
$checkids['id']=$this->input->post('id');
//根据逗号将$checkids['id']拆解,并形成新ID集合$set_new_id
$set_new_id=explode(',', $checkids['id']);
//从数据库中取得的现有的ID的集合$set_old_id
$set_old_id=$this->m_checkout->acquire_old_id();
//print_r($set_old_id);
//将$set_new_id 中的id一个个拿出来,在$set_old_id 中作对比。将在$set_old_id 中没有的ID存入数据库
for ($i=0; $i < count($set_new_id); $i++) {
if(in_array($set_new_id[$i], $set_old_id)){
//当前数据库中有的
echo "ID: ".$set_new_id[$i]." 存在<br>";
$this->load->view('checkout/v_test');
}else{
//将当前数据库中没有的写进数组$checkout[]
$checkout[$i]=$set_new_id[$i];
}
}
print_r($checkout);
//$this->m_checkout->add_new_id($checkout);
}
我传入的值:
123,1233
print_r($set_old_id):
Array ( [0] => Array ( [ID] => 1 ) [1] => Array ( [ID] => 12 ) [2] => Array ( [ID] => 123 ) [3] => Array ( [ID] => 1234 ) [4] => Array ( [ID] => 12345 ) )
打印出来的:
ID: 123 存在
Array ( [0] => 123 [1] => 1233 )
问题:为什么print_r($checkout);还会有123
我明明进行了筛选。
望大神告知。。谢谢
解决方案
首先 $set_old_id
格式是不对的,另外在使用 in_array
函数时需要注意它的一些怪异行为,手册中有很多例子展示了该函数在使用时需要注意的地方,不凡参考一下手册 in_array。
如果 $set_old_id
格式正确的话,也就是把 ID 提取出来,形成一个一维数组,如:[1,2,3,4]。那么在使用 in_array 函数时,这里需要使用上第三个参数,它意味着进行严格匹配(类型及值都需要完全一样)。如:
in_array($set_new_id[$i], $set_old_id, true)
这样子才能准确判断一个值是否存在一个数组里,当然也可以用其他方法,比如 isset()
等等,PHP手册有许多案例。
以前自己在使用 in_array()
过程中也中过招,记录在这里PHP 中的一些 陷阱。
这篇关于php - in_array()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文