Avel
Avel

Reputation: 111

PHP how to parse JSON data double bracket without key in foreach loop

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]]" }

Upvotes: 0

Views: 206

Answers (2)

axiac
axiac

Reputation: 72306

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.

Upvotes: 1

James Shisiah
James Shisiah

Reputation: 383

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) { 
    
    } 
    
  }

Upvotes: 0

Related Questions