'Parsing JSON File to array in PHP
I am currently trying to read co-ordinates from a JSON file and save them to an array for further use. However I am not managing to read the file successfully. my JSON file has the following format(I am only concerned with cX and cY):
{
"cX": [
246,
1253,
1464,
1183
],
"cY": [
223,
138,
383,
114
],
"scroll": [
0,
90,
0,
0
],
"sessionID": [
"f06807c10fb31d5530ad8c4236b94ee2",
"f06807c10fb31d5530ad8c4236b94ee2",
"f06807c10fb31d5530ad8c4236b94ee2",
"f06807c10fb31d5530ad8c4236b94ee2"
],
"Time": [
"11:30:01",
"11:30:02",
"11:30:03",
"11:30:03"
],
"elem": [
"H1",
"H1",
"H1",
"BODY"
]
}
I am attempting to use the following php code:
<?php
$string = file_get_contents("./PHP/JSON/clicks.json");
$json_a = json_decode($string, true);
for($idx = 0; $idx < count($json_a); $idx++){
$obj = (Array)$json_a[$idx];
echo $obj["cX"];
?>
Solution 1:[1]
<?php
$string = file_get_contents("./PHP/JSON/clicks.json");
$json_a = json_decode($string);
$cx = $json_a->cX;
$cy = $json_a->cY;
?>
I hope this help you.
Solution 2:[2]
Looks like you're trying to iterate through an object instead of an array. If you put square brackets around the json, your script should be working. Otherwise read the cX and cY properties without iterating through the object
$obj = $json_a["cX"];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Oliver N. |
Solution 2 | JohnCambell |