【问题标题】:Best way to serialize a JOIN SQL query to JSON将 JOIN SQL 查询序列化为 JSON 的最佳方法
【发布时间】:2015-09-01 05:58:48
【问题描述】:

我找不到适合我的问题的标题。我正在做一个 Restful API /JSON

我的问题是:

我有两张桌子:

Product: id, name
Prices: id_product, price

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

所以,如果我想以 JSON 格式导出下一个信息

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

我做下一个查询:

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

我得到了下一个结果:

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

我使用 PHP,codeigniter。有没有办法以良好的 JSON 格式进行转换?因为我必须重建结果,所以:

        $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'];
        }

创建格式良好的 JSON

【问题讨论】:

  • 不知道你的意思?把你的数组写成$this->output ->set_content_type('application/json') ->set_output(json_encode($resultData));
  • 是的,我可以这样做,但是我将输出五个对象 Json(在这种特殊情况下),因为每一行都是一个对象 json。而且我只有两个(在我的示例中),因此我必须在 json 编码输出之前构建我的对象 json

标签: php mysql json codeigniter join


【解决方案1】:

我会这样做(假设您的价格表中有多行)。与您的操作方式相比,我发现这样做更干净。这可以是模型类中的一个方法

$this->db->select("id, name");
$this->db->from("product");
$q = $this->db->get();
$products = $q->result();
foreach ($products as $product) {
    $this->db->select("price");
    $this->db->from("prices");
    $this->db->where("id_product", $product->id);
    $q = $this->db->get();
    $product->prices = $q->result();
}

$json = json_encode($products);
var_dump($json);

【讨论】:

  • 所以...如果您有 1000 种产品,请进行 1000 次查询。也许更清晰但效率很低
【解决方案2】:

使用 PHP 对 SQL 的结果进行排序是一种正常的做法,因此您的方法是正确的。

    $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))));

【讨论】:

  • 好吧。谢谢。我认为我做了很多样板代码。
  • @jlmg5564 没问题。如果您同意,请不要忘记将答案标记为解决方案;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-31
  • 2014-07-19
  • 1970-01-01
  • 1970-01-01
  • 2012-04-30
  • 2022-07-08
  • 2018-08-20
相关资源
最近更新 更多