ActiveRecord使用三个表获取数组内部数组

时间:2014-04-08 12:33:43

标签: json codeigniter activerecord

我试图在Codeigniter框架中使用ActiveRecord系统输出json字符串。 我的json字符串的正确语法必须是:

{
"data": [
    [
        {
            "name": "xxxx",
            "city": "xxx",
            "address": "xxx",
            "image": "xxx",
            "marketId": "1",
            "products": [
              "Id": "36",
              "productId": "36",
              "price": "120",
              "discounts": "1",
              "title": "xxx",
              "category": "2",
              "weight": "12.5",
              "code": "EA123",
              "isUnitized": "0",
              "description": "xxxx",
              "changed": "2014-04-08 15:09:16",
              "units": "xxx"
            ]
        }
    ]
]

关注"产品"阵列

但是我从代码中得到的字符串不正确,这是错误的字符串:

{
"data": [
    [
        {
            "name": "xxx",
            "city": "xxx",
            "address": "xx x",
            "image": "xxx",
            "marketId": "1",
            "Id": "36",
            "productId": "36",
            "price": "120",
            "discounts": "1",
            "title": "xxx",
            "category": "2",
            "weight": "12.5",
            "code": "EA123",
            "isUnitized": "0",
            "description": "xxx",
            "changed": "2014-04-08 15:09:16",
            "units": "xxx"
        }
    ]
]

您可以看到产品数组不像数组那样显示,而是作为主数组中的常规字符串。

以下是我构建的代码:

$this->db->select('*');
$this->db->from('markets');
$this->db->where("markets.marketId", $marketId);
$this->db->join('linkedPrices', 'linkedPrices.marketId = markets.marketId');
$this->db->join('products', 'products.Id = linkedPrices.productId');
$this->db->order_by("linkedPrices.price", "DESC");
$output[] = $this->db->get()->result();

所以你可以在这里看到表之间的连接。目标是将产品表显示为市场数组中的单个数组,如json字符串的顶部示例所示。

1 个答案:

答案 0 :(得分:0)

不,不是这样,您可以通过循环结果并获取相关的产品数据来获得数据集,这可以通过循环结果获取相关的产品数据

$result=new stdClass();
$this->db->select('*');
$this->db->from('markets');
$this->db->where("markets.marketId", $marketId);
$this->db->join('linkedPrices', 'linkedPrices.marketId = markets.marketId');
$this->db->order_by("linkedPrices.price", "DESC");
$result = $this->db->get()->result();

foreach($result as $r){
$result->products=$this->db->select('*')
       ->from('products')
       ->where('id',$r->productId)
       ->get()
       ->result();
}
$output[]=json_encode($result);