php - 使用数据库中的值生成对象数组
问题描述
假设我有这张桌子:
id | product_item | head_count
1 | 400 | 2
2 | 401 | 5
所需的输出:
[
{"product_item": 400,"head_count": 2},
{"product_item": 401,"head_count": 5}
]
如何使用 Laravel 或 Eloquent 制作所需的输出?
解决方案
Follow bellow step
(1) declare in your controller **use DB**
(2) write Query:
$product = DB::table('tablename')->select('col1','col2')->get();
(3)dd($product); OR print_r($product);
You got the result in $product
echo json_encode($product);
OR if you are load your view then,
return view('VIEW_NAME',compact('product'));
OR return like this and got the result on your view file.
return response()->json($product);
I hope its help.
推荐阅读
- java - Android使用时区检查打开和关闭时间之间是否已过
- php - 查看 Wordpress 私人页面一次以获取操作表单
- git - 如何列出特定文件已有的所有 SHA1 哈希
- c++ - centos/rhel 系统上的 Cmake 安装到 .../lib64,而在 ubuntu 上安装到 .../lib
- python - 获取浮点数组中的最小值,直到它在python中用尽
- php - 引导表数据表中的数据属性导致无限循环
- python - 在 python 请求中传递 ip 地址而不是 url 链接
- python - 如何从 csv 文件中提取最后一个交易日?
- node.js - MongoDB查找元素
- ruby-on-rails - Ruby gem 持久值