I figured out how to get my desired result (almost). My code adds a comma at the end before the last ] so it wont quite work. I know I can use Json_encode to build my array from my external json but I’m stumped. I either need to remove the last comma or use json_encode (which i’m lost on) any better ideas?
Code:
Original JSON
[
{
"timestamp": 1383609600,
"localTimestamp": 1383609600,
"issueTimestamp": 1383609600,
"fadedRating": 4,
"solidRating": 0,
"swell": {
"minBreakingHeight": 4,
"absMinBreakingHeight": 3.836,
"maxBreakingHeight": 6,
"absMaxBreakingHeight": 5.992,
"unit": "ft",
"components": {
"combined": {
"height": 7,
"period": 13,
"direction": 82.64,
"compassDirection": "W"
},
"primary": {
"height": 7,
"period": 13,
"direction": 72.94,
"compassDirection": "WSW"
}
}
}
]
PHP to get the desired result
<?php
$url = 'http://magicseaweed.com/api/API_KEY/forecast/?spot_id=1';
$JSON = file_get_contents($url);
$data = json_decode($JSON,true);
echo "[";
foreach ($data as $record) {
echo "[";
echo "{$record['timestamp']}";
echo ",";
echo "{$record['swell']['absMinBreakingHeight']}";
echo "]";
echo ",";
}
echo "]";
?>
Returns: desired result minus last comma(edited for length)
[
[
1383609600,
3.836
],
[
1383620400,
4.081
],
]
what is the best way to proceed?
Advertisement
Answer
At the risk of answering without a clear question, just build an array of what you want and encode it:
foreach ($data as $record) {
$array[] = array($record['timestamp'], $record['swell']['absMinBreakingHeight']);
}
echo json_encode($array);