douwei8672 2014-07-09 15:20
浏览 23
已采纳

将两个查询合并到一个JSON对象

I have two queries:

1) $result = $this->_db->get_where("wishes",array("is_open"=>1))->result_array();
2) $requirements_result = $this->_db->get("requirements")->result_array();

I'm trying to output the data in this JSON format:

{
    [
      {
        id:12,
        title:"Meet Messi",
        image_url:"http://dsadsa.dsadsa",
        previewImageUrl:"http://kdjfla.com"
        is_open:"true"
        requirements: [
      {
        id: 123,
        title:"kiss Messi",
        is_complete: true
      }
    ]
      }

    ]
  }
}

I created two models (one for each query). This is what I've done so far:

$result = $this->_db->get_where("wishes",array("is_open"=>1))->result_array();
$requirements_result = $this->_db->get("requirements")->result_array();

$return_array = array();
foreach ($result as $value)
{                   
    $wishes_model = new wishes_model(); 
    $wishes_model->init_wishes($value);
    $return_array[] = $wishes_model;
}
return $return_array;

How to i insert the requirements result to create this JSON?

  • 写回答

3条回答 默认 最新

  • dongyan7172 2014-07-09 15:39
    关注

    First, create your wishes array as an associative array, with the ID as the key:

    $wishes_array = array();
    foreach ($results as $value) {
        $wishes_model = new wishes_model();
        $wishes_model->init_wishes($value);
        $wishes_array[$value['id']] = $wishes_model;
    }
    

    Then you can add the requirements to the appropriate wish:

    foreach ($requirements_results as $req) {
        $wishes_array[$req['wish_id']]->requirements[] = $req;
    }
    

    I'm making some assumptions about which things in your application are associative arrays versus objects. You should be able to adjust this to match your specific implementation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器