duanba4942 2018-08-14 13:48
浏览 83

加入/合并/组合JSON数据与PHP / Laravel

This is my JSON output:

array:2 [
    0 => "[{"subject":"Science","date":"2018-08-09 13:03:14","average":4},{"subject":"Science","date":"2018-09-13 13:18:58","average":4}]"
    1 => "[{"subject":"Social","date":"2018-08-14 05:59:56","average":4}]"
]

What I want:

[{"subject":"Science","date":"2018-08-09 13:03:14","average":4},{"subject":"Science","date":"2018-09-13 13:18:58","average":4},{"subject":"Social","date":"2018-08-14 05:59:56","average":4}]

I am not certain how to achieve this. I have tried array_merge, array_combine, array_map, json_encode, json_decode—and various combinations of them all! I am obviously missing something.

Here's my code:

// $classroom_subjects references a table, listing subjects
// for each subject, get the assessment data
foreach ($classroom_subjects as $subject) {
    $loop_graph_data[] = AssessmentData::select('subjects.short_name as subject', 'assessment_data.created_at as date', 'assessment_data.assessed_level as average')
        ->join('subjects', 'subjects.id', 'assessment_data.subject_id')
        ->where('assessment_data.subject_id', $subject->subject_id)
        ->where('assessment_data.student_id', $student_id)
        ->whereBetween('assessment_data.created_at', [$current_term->term_start." 00:00:01", $current_term->term_end." 23:59:59"])
        ->get()
        ->toJson();
}

// create an empty variable
$kept_data = [];

// loop through each of the assessment_data elements and only
// keep the one's that have data (no empty arrays)
foreach($loop_graph_data as $graph_data) {
    if ($graph_data != "[]") {
        $kept_data[] = $graph_data;
    }
}

I want to "join" the two (or more—this is dynamic) arrays together into one seamless JSON formatted string.

Does someone know how to do this?

  • 写回答

2条回答 默认 最新

  • douchuoxuan3177 2018-08-14 13:53
    关注

    Something like json_encode(array_merge(json_decode($a, true),json_decode($b, true))) should work.

    do inside your foreach

    please refer to this similar issue: Merging two json in PHP

    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站