我有一个带有时间和ID的数组,我正在使用不同的id添加新的时间,我需要先检查它是否存在。离。
$times = array(
array('start'=>"1:00","end"=>"1:59","id"=>1),
array('start'=>"2:00","end"=>"2:59","id"=>1),
array('start'=>"3:00","end"=>"3:59","id"=>1),
array('start'=>"4:00","end"=>"4:59","id"=>1),
array('start'=>"5:00","end"=>"5:59","id"=>1),
array('start'=>"6:00","end"=>"6:59","id"=>1)
);
$time = array('start'=>"2:00","end"=>"2:59","id"=>2);
if(!in_array($time,$times){ // here is the problem
array_push($times,$time);
}
这不是重复的,因为它不是关于对键/值,因为它总是相同的关于具有相同的键/值对但是检查一个新元素 - 不管它的id键值 - 是否已经存在于数组中
答案 0 :(得分:4)
由于id
键不同,因此不能直接使用数组比较函数和运算符。我建议简单地迭代数组并比较键:
$found = false;
foreach ($times as $key => $t) {
if ($t['start'] == $x['start'] && $t['end'] == $x['end']) {
$found = true;
$times[$key] = $x;
break;
}
}
if (!$found) {
$times[] = $x;
}
如果字段数很大,甚至未知,您可以创建id
字段未设置的临时数组,并将它们与比较运算符进行比较:
$tmp_x = $x;
unset($tmp_x['id']);
$found = false;
foreach ($times as $key => $t) {
$tmp_t = $t;
unset($tmp_t['id']);
if ($tmp_t == $tmp_x) {
$found = true;
$times[$key] = $x;
break;
}
}