简体   繁体   中英

How can I access the values directly from json file with php

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

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

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.

Based on your JSON data, this will work to pull out your data.

$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";
        }
}

If I understand what you mean, you can use $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
}

Here you have access to all the keys and values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM