douwei8672
douwei8672
2014-07-09 15:20

将两个查询合并到一个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 dongyan7172 7年前

    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.

    点赞 评论 复制链接分享
  • drddx3115 drddx3115 7年前

    I have couple of question but for now i am gonna guess. You can try array_merge but it will overwrite same keys. If you don't want that you can add prefix to keys and then merge both array.

    And i think rest of the solutions you already have in here.

    点赞 评论 复制链接分享
  • dta25920 dta25920 7年前

    Hi like you have 2 results say result1 and result2

    you can make 2 foreach loop for each and store them in two different array and then you make pass it in result and encode it.

    see how it works:

    foreach ($result1 as $res)
    {
        $result_s1[]=$res;
    }
    foreach($result2 as $cmd)
    {
       result_s1[]=$cmd;
    }
    $resultdata[]=array_merge($result_s1,$result_s2)
    
    点赞 评论 复制链接分享

相关推荐