如何在laravel中合并两个相似的对象

时间:2017-05-02 16:45:55

标签: php json laravel object

我在这里需要帮助。我有两个相似的对象,我想将它们合并到laravel中的一个对象中。怎么做?

这是我的对象

{"course_code":"UGRC110","venue_id":22,"exam_date":"May 6, 2017","exam_time":"3:30 pm","student_no":400}

{"course_code":"UGRC110","venue_id":25,"exam_date":"May 6, 2017","exam_time":"3:30 pm","student_no":700}

我想合并并获得类似的东西

{"course_code":"UGRC110","venue_id":[22,25],"exam_date":"May 6, 2017","exam_time":"3:30 pm","student_no":[400,700]}

我想将venue_id和student_no合并在一起..任何帮助都将是 非常感谢..谢谢

1 个答案:

答案 0 :(得分:1)

希望这会帮助你。在这里,我们只使用简单的foreach来合并这两个json

Try this code snippet here

<?php

$json1 = '{"course_code":"UGRC110","venue_id":22,"exam_date":"May 6, 2017","exam_time":"3:30 pm","student_no":400}';
$json2 = '{"course_code":"UGRC110","venue_id":25,"exam_date":"May 6, 2017","exam_time":"3:30 pm","student_no":700}';

json_merge($json1, $json2);
function json_merge($json1, $json2)
{
    $array1 = json_decode($json1, true);
    $array2 = json_decode($json2, true);
    $result = array();
    foreach ($array1 as $key => $value)
    {
        if ($array1[$key] == $array2[$key])
        {
            $result[$key] = $array2[$key];
        } else
        {
            $result[$key][] = $array1[$key];
            $result[$key][] = $array2[$key];
        }
    }
    return json_encode($result, JSON_PRETTY_PRINT);
}

<强>输出:

{
    "course_code": "UGRC110",
    "venue_id": [
        22,
        25
    ],
    "exam_date": "May 6, 2017",
    "exam_time": "3:30 pm",
    "student_no": [
        400,
        700
    ]
}