dtx6087 2016-04-19 12:33
浏览 95
已采纳

比较2个PHP数组并过滤掉结果

I've been struggling for a while now. I have 2 arrays that I want to compare with each other. A user array and a lesson array. The Keys in the lesson array are the ID's of that lesson

Lesson Array:

Array(
    // The key in this array ([143] or [13]) is the lesson ID each lesson contains one ore more topics
    [143] => Array (
        [0] => 315 // example: 315 is a topic ID within lesson 143
        [1] => 311
        [2] => 176
        [3] => 145
    )

    [13] => Array (
        [0] => 27
        [1] => 25
    )
)

The user array contains only the information about which topics that user has completed. Topic with lesson ID's that are not completed don't exist in this array.

Main question: I want to compare the topic ID's of the user array to the Lesson array. And I want to put the topics that aren't completed in a seperate array.

User array

Array (
    [0] => Array (
        [143] => Array (
            [145] => 1 // (this 1 means it is completed, this key is a topic ID)
            [176] => 1
        )
    )

    [1] => Array (
        [13] => Array (
            [25] => 1
        )
    )

)

In this example above the result i want to get is an array with non matching id's like:

$result = array( 143 => array(311,315), 13 => array(27))

I hope it's a little bit clear.

If anyone can point me out in the right direction I'll be very glad! I tried a lot of things but to post them all here it's not clarifying the main question.

  • 写回答

2条回答 默认 最新

  • doutui6644 2016-04-19 12:59
    关注

    you have to use array_keys and array_diff. Online compile at My answer

    Arrays

    $lesson = array(
        "143" => array("315", "311", "176", "145"),
        "13" => array("27", "25")
    );
    
    $user = array(
        array("143" => array("145" => "1", "176" => "1")),
        array("13" => array("25" => "1"))
    );
    

    Mechanism/ process

    $result = array();
    foreach ($user as $key => $value) {
        foreach ($value as $key2 => $value2) {
            $result[$key2] = array_diff($lesson[$key2], array_keys($value2));
        }
    }
    

    Result

    echo '<pre>';
    print_r($result);
    echo '</pre>';
    

    Output

    Array
        (
            [143] => Array
            (
                [0] => 315
                [1] => 311
            )
            [13] => Array
            (
                [0] => 27
            )
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名