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 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化