这是我的JSON输出:
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}]"
]
我想要什么:
[{"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}]
我不确定如何实现这一目标。我尝试了array_merge,array_combine,array_map,json_encode,json_decode以及它们的各种组合!我显然缺少了一些东西。
这是我的代码:
// $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;
}
}
我想将两个(或更多-这是动态的)数组“连接”在一起,成为一个无缝的JSON格式的字符串。
有人知道该怎么做吗?
答案 0 :(得分:0)
像json_encode (array_merge(json_decode($a, true),json_decode($b, true)))
之类的东西应该可以工作。
深入foreach
请参考以下类似问题: Merging two json in PHP
答案 1 :(得分:0)
我最终不得不对array_flatten数据加倍。这是我使用的解决方案:
// get all the data for making a graph
// it needs to be compiled by subject
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();
}
$kept_data = [];
foreach($loop_graph_data as $graph_data) {
if ($graph_data != "[]") {
$kept_data[] = $graph_data;
}
}
$flattened = array_flatten(array_flatten($kept_data));
$flattened = json_encode($flattened);
dd($flattened);
输出:
[{“ subject”:“ Science”,“ date”:“ 2018-08-09 13:03:14“,”平均值“:4},{”主题“:”科学“,”日期“:” 2018-09-13 13:18:58“,”平均值“:4},{”主题“:”社交“,”日期“:” 2018-08-14 05:59:56“,”平均值“:4}]