如何将Laravel控制器中的数组格式转换为JavaScript所需格式
解决Laravel查询结果转指定JavaScript数组格式的问题
问题分析
你的代码存在两个核心问题:
pluck('total', 'c.course_code')中的c.course_code无效,因为未给courses表定义别名c;pluck返回的是关联数组(键为课程代码、值为总数),无法直接生成你需要的二维数组结构。
修正后的控制器代码
$data = DB::table('courses') ->selectRaw('courses.course_code, COALESCE(COUNT(student_applicants.status), 0) as total') ->leftJoin('student_applicants', function ($join) { $join->on('courses.id', '=', 'student_applicants.course_id') ->where('student_applicants.status', '=', 1) ->where('student_applicants.award_applied', '=', 1); }) ->groupBy('courses.course_code') ->get() ->map(function ($item) { // 转换为[课程代码, 总数]的二维数组结构 return [$item->course_code, (int)$item->total]; }) ->toArray(); return view('admin.dashboard', ['data' => $data]);
关键调整说明
- 用
COALESCE函数把COUNT返回的null(无匹配数据的课程)强制转为0; - 放弃
pluck,改用get()获取完整集合,再通过map将每条记录转换为目标子数组格式; - 将
total转为整数类型,避免JS中出现字符串格式的数字。
视图中转换为JavaScript数组
在Blade视图里直接用json_encode把PHP数组转成标准JS数组:
<script> const courseData = {!! json_encode($data) !!}; // 输出结果就是你需要的格式: // [["BSA", 0], ["BSBA-HR", 0], ...] </script>
内容的提问来源于stack exchange,提问作者Sharmae Reyes
相关产品推荐
相关产品推荐

