Som
Som

Reputation: 970

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

Upvotes: 0

Views: 62

Answers (3)

Chris Forrence
Chris Forrence

Reputation: 10104

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.

Upvotes: 2

4EACH
4EACH

Reputation: 2197

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.

Upvotes: 0

jpaddock
jpaddock

Reputation: 21

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

Upvotes: 1

Related Questions