dongxu3029 2014-06-15 19:47
浏览 88
已采纳

找出在数组中添加和删除的项目

I'm building application that tells user which are old and which are new bank notes when I increase sum with X. Everything is fine, but I'm wondering how I can now get list of added and removed items of array?

$old = array(1,5,10);
$new = array(1,5,1);

$added = array_diff($new,$old);
$removed = array_diff($old,$new);

And this is what code above returns:

  • $added is array(). Incorrect, it should be array([2] => 1).
  • $removed is array([2] => 10). Correct.

What am I doing wrong, and how can I fix it?

  • 写回答

2条回答 默认 最新

  • doudu4282 2014-06-15 19:54
    关注
     $added = array_diff($new,$old);
    

    In the above statement, array_diff() compares $new with $old and returns the values in $new that are not present in $old. There is no such value, and hence it returns an empty array.

    In short, array_diff() doesn't work with duplicate values. You will have to write a custom function to achieve this. Here's an example:

    function array_diff_once($array1, $array2) {
        foreach($array2 as $val) {
            if (false !== ($pos = array_search($val, $array1))) {
                unset($array1[$pos]);
            }    
        }
        return $array1;
    }
    

    You can simply use it the same way you did before:

    $added   = array_diff_once($new,$old);
    $removed = array_diff_once($old,$new);
    

    print_r() of these arrays would correctly output:

    Array
    (
        [2] => 1
    )
    Array
    (
        [2] => 10
    )
    

    Working demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案