dongtan4046 2014-03-06 19:07
浏览 85
已采纳

如何使用php直接从json文件访问值

Currently I have the following code.

<?php
$jsonFP = '[{"Maths":{"earlierMarks":85,"currMarks":90}},{"Physics":{"earlierMarks":80,"currMarks":85}},{"Science":{"earlierMarks":82,"currMarks":85}},{"Social":{"earlierMarks":75,"currMarks":60}}]';

$histData=json_decode($jsonFP,true);
print_r($histData);
$subject_list = array("Social","Maths","Physics");

foreach($subject_list as $subject){
        print_r($histData[$subject]);
        echo "
";
}
?>

But this print_r($histData[$subject]); statement expects index like this print_r($histData[some index][$subject]);

How can I access the values in $histData dynamically while looping for $subject_list

  • 写回答

3条回答 默认 最新

  • dongyue934001 2014-03-06 19:32
    关注

    If you're alright with changing your input ($jsonFP), you can restructure it to remove the array and have it just be an object:

    $jsonFP = '{"Maths":{"earlierMarks":85,"currMarks":90},"Physics":{"earlierMarks":80,"currMarks":85},"Science":{"earlierMarks":82,"currMarks":85},"Social":{"earlierMarks":75,"currMarks":60}}';
    
    $histData = json_decode($jsonFP, true);
    
    echo $histData['Maths']['earlierMarks']; // prints 85
    echo $histData['Social']['currMarks']; // prints 60
    

    Because you no longer have an array, you can access the elements in it without needing the numbered index.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集