【问题标题】:Laravel Collection/Array find the difference between two resultsLaravel Collection/Array 找出两个结果之间的差异
【发布时间】:2021-12-10 04:47:37
【问题描述】:

我一直试图找出两个集合之间的区别:

第一:

{
    "name": "Test A",
    "scores": [
        {
            "name": "Values",
            "points": 9
        },
        {
            "name": "Algebra",
            "points": 6
        },
        {
            "name": "Science",
            "points": 5
        },
        {
            "name": "Total",
            "points": 20
        }
    ]
}

第二次:

{
    "name": "Test A",
    "scores": [
        {
            "name": "Values",
            "points": 5
        },
        {
            "name": "Algebra",
            "points": 8
        },
        {
            "name": "Total",
            "points": 13
        }
    ]
}

我的目标是在第一个集合的基础上创建一个包含缺失键和值对的新集合,保留其值,缺失键的值为 0。我想要实现的输出是:

{
    "name": "Test A",
    "scores": [
        {
            "name": "Values",
            "points": 5
        },
        {
            "name": "Algebra",
            "points": 8
        },
        {
            "name": "Science",
            "points": 0
        },
        {
            "name": "Total",
            "points": 13
        }
    ]
}

使用diffKeys 方法:

$collection_new = $collection_1['scores']->diffKeys($collection_2['scores']);
dd($collection_new->all());

这将导致:

{
    "4": {
        "name": "Total",
        "points": 20
    },
}

需要您的出色投入。谢谢。

【问题讨论】:

    标签: arrays laravel collections


    【解决方案1】:

    下面的函数应该可以工作,但是第一个数组应该包含第二个数组的所有分数。

    $first['scores'] = mergeScores();
    
    function mergeScores()
    {
         return array_map(
             fn ($x) => array_merge($x, getPoint($x['name'])), 
             $first['scores']
         );
    }
    
    function getPoint($name)
    {
        $score = array_filter($second, fn ($x) => $x['name'] == $name);
        return ['point' => empty($score) ? 0 : $score['score']];
    }
    

    【讨论】:

    • 这是有效的。非常感谢!
    猜你喜欢
    • 2021-12-05
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 2022-01-04
    相关资源
    最近更新 更多