user3282988
user3282988

Reputation: 129

Merging two queries to one JSON object

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?

Upvotes: 0

Views: 1127

Answers (3)

Ruchi S
Ruchi S

Reputation: 31

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)

Upvotes: 0

Harry
Harry

Reputation: 44

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.

Upvotes: 0

Barmar
Barmar

Reputation: 781096

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.

Upvotes: 1

Related Questions