Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - combining json with json_decode

Tags:

json

php

I'm trying to combine multiple JSON objects into a single one in PHP. I'm iterating through the JSON objets, decoding them, parsing out the parts I want to keep, and storing them in a property in my php class.

Supposing my json objects look like the following format:

{
    "lists" : {
        "list" : [
            {
                "termA" : 2 ,
                "termB" : "FOO" 
            } 
        ] 
    } 
}

I want to eventually combine everything into a JSON object like so.

{
    "lists" : {
        "list" : [
            {
                "termA" : 2 ,
                "termB" : "FOO" 
            },
            {
                "termA" : 2 ,
                "termB" : "FOO" 
            } 
        ] 
    } ,
    "lists" : {
        "list" : [
            {
                "termA" : 4 ,
                "termB" : "BAR" 
            },
            {
                "termA" : 4 ,
                "termB" : "BAR" 
            } 
        ] 
    } 
}

I'm trying to store Arrays in a property within my class in a function that gets called iteratrivley:

   private function parseData($json){
        $decodeData = json_decode($json);
            $list = $decodeData->lists;
        $this->output .= $list
    }

However I get the following error during the "$this->output .= $list" line.

Object of class stdClass could not be converted to string

Right now $this->output has no initial value. What might be the best way to store the "list" arrays temporarily, and then reformat them after going through all of the json objects?

Thanks.

like image 320
minimalpop Avatar asked Apr 15 '26 11:04

minimalpop


1 Answers

You were close:

private function parseData($json){
  $decodeData = json_decode($json);
  $list = $decodeData['lists'];
  $this->output .= $list
}
like image 57
cletus Avatar answered Apr 17 '26 02:04

cletus