Here's an example (I did alter the values) of JSON data that I'm getting from an API:
{"status":"OK","data":{"trends":{"uv":[{"date":"201303","value":1},{"date":"201304","value":2},{"date":"201305","value":31},{"date":"201306","value":4},{"date":"201307","value":4},{"date":"201308","value":9},{"date":"201309","value":12},{"date":"201310","value":43},{"date":"201311","value":14},{"date":"201312","value":73},{"date":"201401","value":78},{"date":"201402","value":65},{"date":"201403","value":52}]},"trends_low_sample":false,"query_cost":13,"trends_frequency":"monthly"}}
How would go about accessing the value in data.trends.uv[number_the_array].date in PHP?
Here's some stuff I've played around with:
$data1 = file_get_contents('/home/strj500/Downloads/result.html');
//echo $data1;
$theData = json_encode($data1);
//$data1 = preg_replace('/,\s*([\]}])/m', '$1', utf8_encode($data1));
//$data1 = utf8_encode($data1);
$result1 = json_decode($theData);
echo $result1->status;
//var_dump($result1);
//echo json_last_error();
//echo error_log();
//echo error_reporting(E_ALL);
/*foreach ($result1->data->trends->rank as $rank
{
echo "{$rank->date}
";
}*/
//echo $result1["data"]["trends"]["uv"];
Maybe another question that goes along with this, if I'm wanting to access JSON later in PHP, what's the best file format to store it in? (JSON, TXT, HTML)? If it helps I'm also going to be passing this json data on mysql.
Loop like this..
<?php
$json='{"status":"OK","data":{"trends":{"uv":[{"date":"201303","value":1},{"date":"201304","value":2},{"date":"201305","value":31},{"date":"201306","value":4},{"date":"201307","value":4},{"date":"201308","value":9},{"date":"201309","value":12},{"date":"201310","value":43},{"date":"201311","value":14},{"date":"201312","value":73},{"date":"201401","value":78},{"date":"201402","value":65},{"date":"201403","value":52}]},"trends_low_sample":false,"query_cost":13,"trends_frequency":"monthly"}}';
$yourobj=json_decode($json);
foreach($yourobj->data->trends->uv as $k=>$arr)
{
echo $arr->date."<br>";
}
OUTPUT:
201303
201304
201305
201306
201307
201308
201309
201310
201311
201312
201401
201402
201403
By using json_decode() with the second parameter as true:
$result1 = json_decode($theData,true);
You will be able to access all the elements as normal arrays. If you want to fetch some specific data for example you could do it as so (In this example we want the index 0):
$result1['data']['trends']['uv'][0];