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

时间:2014-03-06 19:07:27

标签: php json

目前我有以下代码。

<?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 "\n";
}
?>

但是这个print_r($ histData [$ subject]);语句需要像这样的print_r索引($ histData [some index] [$ subject]);

如何在为$ subject_list

循环时动态访问$ histData中的值

3 个答案:

答案 0 :(得分:2)

如果您可以更改输入($jsonFP),则可以重新构建它以删除数组并将其作为对象:

$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

因为您不再拥有数组,所以您可以访问其中的元素而无需编号索引。

答案 1 :(得分:1)

根据您的JSON数据,这将有助于提取您的数据。

$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);
echo "<br/>";

foreach($histData as $subject){
        print_r($subject);
        echo "<br/>\n";
        foreach($subject as $key => $value){
            echo "subject == $key<br/>\n";
            echo "earlierMarks == ".$value['earlierMarks']."<br/>\n";
            echo "currMarks == ".$value['currMarks']."<br/>\n";
        }
}

答案 2 :(得分:0)

如果我理解你的意思,你可以使用$subject_list

$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);

foreach($histData as $subject_key => $subject_value) {
    if(is_array($subject_value)) {
        foreach($subject_value as $key => $value) {
            //do something with key and value
        }
        continue;
    }
    //do something with $subject_key and $subject_value
}

您可以访问所有键和值。