【问题标题】:Hash Style Array to Compare 2 Arrays哈希样式数组以比较 2 个数组
【发布时间】:2013-05-20 00:10:47
【问题描述】:

我喜欢将数据库中的一个数组与另一个数组进行比较,以使用issetarray_key_exists 生成一个缺少ID 的新数组。这是我正在创建的数据库中的数组。

foreach ($listings as $listing) {
    $local_ids[$listing['id']] = 'true';
}

$local_ids = array(
    '567' => true,
    '568' => true,
    '569' => true,
    '570' => true,
    '571' => true,
    '572' => true,
    '573' => true
);

$new_ids = array(
    '568',
    '569',
    '572',
    '573',
    '574',
    '575',
    '576',
    '577'
);

拿上面的两个数组,我想循环通过它们给我一个567, 570, 571被删除的结果。

我更改了 $new_ids,因为此列表可能包含也可能不包含新的 ID,并且不在 $local_ids 中。这些可以忽略,我只需要删除那些。

【问题讨论】:

  • array_diff() 会这样做。
  • 我会试试,这对 30,000 多个结果进行比较有用吗?
  • 运行时间不长,但它确实返回了所有存在的键,而不是丢失的键。
  • 我尝试了这两种方法,它们给出的结果规模较小。在大范围内它起作用,结果是不正确的。

标签: php isset array-key-exists


【解决方案1】:

我知道这样的方法

<?php
$a1 = array("a" => "one", "two", "three", "four");
$a2 = array("b" => "one", "two", "three");
$result = array_diff($array1, $array2);

print_r($result);
?>
or

<?php
$a1 = array("a" => "one", "b" => "two", "c" => "three", "four");
$a2 = array("a" => "one", "two", "three");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 2021-10-16
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    相关资源
    最近更新 更多