比较在PHP两个数组 [英] comparing two arrays in php

查看:96
本文介绍了比较在PHP两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这个code:

  $ =新阵列(
     123=> 一个,
     456=> b的
 ); $旧=阵列(
     123=> 一个,
     456=> b的
 );

那么 $新的阵列变成这个样子:

  $ =新阵列(
     456=> b的,
     123=> C,
     789=> E
 );

当你看到的计数 $新的阵列增加和改变元素的顺序,并在关键值 123 也发生了变化。我需要比较 $新的 $旧阵列阵列并赶上仅在关键的值所做的更改 123 ,而无需关心顺序和元素的数量。我想:

  $结果=和array_diff($新,老$);
 的print_r($结果);

输出:

 阵列([123] => C [789] => E)


解决方案

更新。相当混乱。现在我认为我们得到了它。

  $ =旧阵列(
    123=> 一个,
    456=> b的
);
$ =新阵列(
    456=> b的,
    123=> C,//抓住这个(即改变了旧数组元素)
    789=> E
);$ NEW2 =阵列();
的foreach($新的一样$关键=> $ new_val)
{
    如果(使用isset($旧[$关键]))//属于旧数组?
    {
        如果($旧[$关键]!= $ new_val)//改变了呢?
            $ NEW2 [$关键] = $新[$关键]; // 抓住它
    }
}//输出$ NEW2:
阵列(
  123 => 'C',

I use this code :

 $new = array(
     "123" => "a",
     "456" => "b"
 );

 $old = array(
     "123" => "a",
     "456" => "b"
 );

then the $new array become like this:

 $new = array(
     "456" => "b",
     "123" => "c",
     "789" => "e"
 );

as you see the count of $new array increased and the order of elements changed and the value at key 123 also changed. I need to compare the $new array against the $old array and catch only the change made on the value at key 123 without caring about the order and the count of elements. I tried:

 $result = array_diff( $new, $old );
 print_r( $result );

output :

 Array ( [123] => c [789] => e )

解决方案

UPDATE. quite confusing. now I think we got it

$old = array(
    "123"    => "a",
    "456"    => "b"
);
$new = array(
    "456"    => "b",
    "123"    => "c", // catch this (element in old array that is changed)
    "789"    => "e"
);

$new2 = array();
foreach ($new as $key => $new_val)
{
    if (isset($old[$key])) // belongs to old array?
    {
        if ($old[$key] != $new_val) // has changed?
            $new2[$key] = $new[$key]; // catch it
    }
}

// output $new2:
array (
  123 => 'c',
)

这篇关于比较在PHP两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆