组合和消除数组中的键值对


Combining and eliminating keys value pairs in array

一个关于数组的PHP问题。假设有两个数组:

[first] => Array
    (
        [0] => users
        [1] => posts
        [2] => comments
    )
[second] => Array
    (
        [users] => the_users
        [posts] => the_posts
        [comments] => the_comments
        [options] => the_options
    )

如何比较这两个数组?意思是,我们如何检查第一个数组中的值是否等于第二个数组中的键(array_flip?)在以某种方式组合它们(array_merge?)之后。无论哪个值/键对匹配,都将其从数组中删除。

基本上,最终结果将是两个数组合并,删除重复项,唯一的索引将是:
[third] => Array
    (
        [options] => the_options
    )

try this:

$third = array_diff_key($second,array_flip($first));

可能有一个内置函数,但如果没有,请尝试:

$third = array();
foreach(array_keys($second) as $item)
  if(!in_array($item, $first))
    $third[$item] = $second[$item];

注意,这是假设$first中没有一个在$second中没有对应键的项。为了解决这个问题,您可以有一个额外的循环(我不知道您将$third中的值设置为这些,可能是null:

)。
foreach($first as $item)
  if(!in_array($item, array_keys($second)))
    $third[$item] = null;

这很简单,而且效率很高:

$third = $second;
foreach($first as $value)
{
    if (isset($third[$value]))
    {
      unset($third[$value]);
    }
}

这就是你问题的答案

$first= array
(
    "0" => "users",
    "1" => "posts",
    "2" => "comments"
);
$firstf=array_flip($first);
$second = array
(
    "users" => "the_users",
    "posts" => "the_posts",
    "comments" => "the_comments",
    "options" => "the_options"
);
$third=array_diff_key($second,$firstf);
print_r($third);