php-如何检查另一个数组中是否存在相似的数组

我有一个包含时间和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键值如何)

解决方法:

由于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;
  }
}
上一篇:python-是否有此代码的替代方法,看起来更整洁并且更易于理解?


下一篇:确保python脚本仍在运行