dqm74406 2015-06-16 12:10
浏览 65
已采纳

将JOIN SQL查询序列化为JSON的最佳方法

I can't find a good title for my question. I'm doing a Restful API /JSON

My problem is:

I have got two tables:

Product: id, name
Prices: id_product, price

Product 1--* Prices (One product have got multiples prices)

So, If I want to export the next information in JSON

products: [
     {
          id:1
          name: chair
          prices: [3.3,5.0,6.0]
     }
      , {
          id:2
          name: apple
          prices: [2.0,5.0]
     } ,..
]

I do the next query:

SELECT product.id, product.name, prices.price FROM procut LEFT JOIN prices ON product.id = prices.id_product

I got the next result:

id  , name  , prices
----------------------
 1    chair    3.3
 1    chair    5.0
 1    chair    6.0
 2    apple    ...
...

I use PHP, codeigniter. Is there a way to transform in a well form JSON? Because I have to rebuild the result, doing:

        $resultArray = $query->result_array();  //CodeIgniter

        foreach($resultArray as $row)
        {
            if(!isset($resultData[$row['id']]))
            {
                $resultData[$row['id']] = $row;
                unset($resultData[$row['id']]['price']);

                $resultData[$row['id']]['prices'] = array();

            }

            $resultData[$row['id']]['prices'][] = $row['price'];
        }

to create the JSON well formed

  • 写回答

2条回答 默认 最新

  • dq8081 2015-06-18 11:20
    关注

    That's a normal practice to sort result from SQL with PHP, so You're on the right way.

        $result = array();
        foreach($query->result_array() as $row)
        {
            $result[$row['id']] = array(
                'id'=>$row['id'],
                'name'=>$row['name'],
                'price'=>isset($result[$row['id']]['price']) ? array_push($result[$row['id']]['price'],$row['price']) : array($row['price'])
            );
        }
    
        $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode(array('products'=>array_values($result))));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 vue3加ant-design-vue无法渲染出页面
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序