Home > Software design >  PHP how to parse JSON data double bracket without key in foreach loop
PHP how to parse JSON data double bracket without key in foreach loop

Time:11-07

This is a REST API Output. I'm trying to access each value in foreach loop in PHP but there is no key and the double bracket is making it so much difficult for me.

Output JSON data: { "time":20211101, "data":" [[1630454700,0.01823,0.01823,0.01823,0.01823,5366.009589], [1630461840,0.01876,0.01877,0.01876,0.01877,5713.905167], [1630462080,0.01877,0.01877,0.01877,0.01877,1039.957378], [1630477560,0.01777,0.01776,0.01778,0.01779,1000.000000]]" }

CodePudding user response:

Use json_decode($text, true) to parse the JSON into an object having the properties time and data.
The value of the data property is a string that is the JSON representation of a bidimensional array. Use json_decode() again on it to extract the array of numbers. Then use foreach() to iterate over the values.

$text = '{ "time":20211101, "data":" [[1630454700,0.01823,0.01823,0.01823,0.01823,5366.009589], [1630461840,0.01876,0.01877,0.01876,0.01877,5713.905167], [1630462080,0.01877,0.01877,0.01877,0.01877,1039.957378], [1630477560,0.01777,0.01776,0.01778,0.01779,1000.000000]]" }';

$parsed = json_decode($text, true);
$data = json_decode($parsed['data'], true);

foreach ($data as $row) {
    echo("| ");
    foreach ($row as $val) {
        echo("$val | ");
    }
    echo("\n");
}

Output:

| 1630454700 | 0.01823 | 0.01823 | 0.01823 | 0.01823 | 5366.009589 | 
| 1630461840 | 0.01876 | 0.01877 | 0.01876 | 0.01877 | 5713.905167 | 
| 1630462080 | 0.01877 | 0.01877 | 0.01877 | 0.01877 | 1039.957378 | 
| 1630477560 | 0.01777 | 0.01776 | 0.01778 | 0.01779 | 1000 | 

Check it online.

CodePudding user response:

You can use two foreach loops since that response has two arrays on that 'data' property, assuming that the JSON response is set to a variable called $response:

foreach($response->data as $value => $key) { 
   
 foreach($value as $item => $key2) { 
    
    } 
    
  }
  • Related