7

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"];
?>
1
  • What is the actual problem ? Commented Feb 19, 2017 at 17:23

2 Answers 2

14
<?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.

Sign up to request clarification or add additional context in comments.

2 Comments

No need of true in json_decode() because it will convert object into array .
Sugges to change this post as it's incorrect: $json_a = json_decode($string, true); results in an associative array and would need to be accessed by $json_a[cX]. Trying to access attribute $json_a->cX results in null. Suggestion: remove the true. Now it cost me 5 minutes to figure out what was going wrong.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.