2017-06-19 112 views
0

我有一个看起来像这样的JSON文件(data.json) - >麻烦与PHP和JSON

{ 
    "level0": [ 

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

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

    ] 
} 

我有一个HTML页面,看起来像这样(的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> 

这仅仅是一个按钮,该按钮时,利用AJAX调用在以下文件中的PHP函数(printJSON.php) - >

<?php 

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

    printJSON(); 

?> 

现在,我已经是现在研究几个小时..我仍然无法理解如何操作这个,以便从这个JSON对象中打印出我想要的。例如,在这里我试图展示level0的第一个元素,但我没有运气。如果任何人都可以向我解释我做错了什么,以及我将如何访问这个JSON对象的任何部分,非常感谢,谢谢。

+0

那么你现在想要输出什么样的东西,你会得到一个错误还是你能看到输出? – zenwraight

回答

2

当你第一次处理一个新的JSON字符串,它是一个好主意,做这个简单的代码来看看是什么样子的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); 

结果

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 
       ) 

     ) 

所以,现在你可以看到你有一个包含子数组的数组,每个子数组都包含一个子关联数组。所以你会从中挑选物品

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