laroy
laroy

Reputation: 153

Trouble With PHP and JSON

I have a JSON file (data.json) that looks like this -->

{
    "level0": [

        {"name": "brandon", "job": "web dev"}, 
        {"name": "karigan", "job": "chef"}
    ],

    "level1": [ 
        {"name": "steve", "job": "father"},
        {"name": "renee", "job": "mother"}

    ]
}

I have an HTML page that looks like this (index.html) -->

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>


    <script type = "text/javascript">
      function myAjax () {
        $.ajax( { type : 'POST',
          data : { },
          url  : 'printJSON.php',              // <=== CALL THE PHP FUNCTION HERE.
          success: function ( data ) {
            console.log(data);               // <=== VALUE RETURNED FROM FUNCTION.
          },
          error: function ( xhr ) {
            alert( "error" );
          }
        });
      }
    </script>


  </head>

  <body>
  <button onclick="myAjax()">Click here</button> <!-- BUTTON CALL PHP FUNCTION -->
  </body>
</html>

which is just a button, that when clicked, utilizes AJAX to call a PHP function in the following file (printJSON.php) -->

<?php

    function printJSON()
    {
        $str = file_get_contents('data.json');
        $json = json_decode($str, true);
        echo $json["level0"][0];
    }

    printJSON();

?>

Now, I've been researching for hours now.. and I'm still having trouble understanding how to manipulate this in order to print out exactly what I want from this JSON object. For example, here I'm trying to display just the first element of level0, but I'm having no luck. If anyone could explain to me what I'm doing wrong and how I would access any part of this JSON object, it would be much appreciated, thank you.

Upvotes: 0

Views: 43

Answers (1)

RiggsFolly
RiggsFolly

Reputation: 94642

When you first deal with a new json string, its a good idea to do this simple code to look at what it looks like in PHP

$s = '{
    "level0": [

        {"name": "brandon", "job": "web dev"}, 
        {"name": "karigan", "job": "chef"}
    ],

    "level1": [ 
        {"name": "steve", "job": "father"},
        {"name": "renee", "job": "mother"}

    ]
}';

$json = json_decode($s,true);

print_r($json);

Result

Array
(
    [level0] => Array
        (
            [0] => Array
                (
                    [name] => brandon
                    [job] => web dev
                )

            [1] => Array
                (
                    [name] => karigan
                    [job] => chef
                )

        )

    [level1] => Array
        (
            [0] => Array
                (
                    [name] => steve
                    [job] => father
                )

            [1] => Array
                (
                    [name] => renee
                    [job] => mother
                )

        )

So now you can see that you have an array containing a sub array, and each sub array contains a sub associative array. So you would pick items from it like this

echo $json['level0'][0]['name'];
echo $json['level0'][0]['job'];

Upvotes: 2

Related Questions