dongpaipu8394 2015-07-06 15:38
浏览 197

JSON数组排序结构

Is there an easy (easier) way to split up my JSON? I'm not so good with JSON but here is my situation;

I have a table of payments and a table of locations. There are 10 payments at location A and 5 payments at location B.

my payments table is like;

CREATE TABLE `payments` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `amount` decimal(15,2) NOT NULL,
  `location_id` int(7) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=63678 DEFAULT CHARSET=latin1;

my locations table is like;

CREATE TABLE `locations` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL DEFAULT '',
  `auth_key` varchar(32) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

So I'd like my JSON to be something like;

location:[

{"A":
"auth_key": "--justanexample--",
"payments":[
    {"id":"1", "amount":"15.15"}, 
    {"id":"3", "amount":"11.85"}, 
    {"id":"4", "amount":"18.95"}
]},

{"B":
"auth_key": "--justanotherexample--",
"payments":[
    {"id":"2", "amount":"15.00"}, 
    {"id":"5", "amount":"12.77"}, 
    {"id":"6", "amount":"13.45"}
]}
]

At the moment, I am using Eloquent and I'm creating two nested loops, first to get all the locations and then to get all the payments per location;

$locations = $app->location->get();

foreach ($locations as $location) {

  $payments = $app->payment->get();

     foreach ($payments as $payment) {

       echo json_encode($payment);    

Or should I use an array function here instead and then encode that?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 linux驱动,linux应用,多线程
    • ¥20 我要一个分身加定位两个功能的安卓app
    • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
    • ¥15 IAR程序莫名变量多重定义
    • ¥15 (标签-UDP|关键词-client)
    • ¥15 关于库卡officelite无法与虚拟机通讯的问题
    • ¥15 目标检测项目无法读取视频
    • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
    • ¥100 求采集电商背景音乐的方法
    • ¥15 数学建模竞赛求指导帮助