Home > database >  How to access json data in php
How to access json data in php

Time:02-22

I hope you can help me with this maybe simple question. So I'm trying to access the data of my the json file below:

[
  {
    "value": "12"
  },
  {
    "value": "94338"
  },
  {
    "value": "3.97"
  },
  {
    "value": "416"
  }
]

So I already have decoded the json file...

<?php
$json_string = file_get_contents("myjson.json");
$json_array = json_decode($json_string, true);
print_r($json_array);
?>

... which gives me the following result:

Array ( [0] => Array ( [value] => 12 ) [1] => Array ( [value] => 94338 ) [2] => Array ( [value] => 3.97 ) [3] => Array ( [value] => 416 ) [4] => Array ( [value] => 230 ) [5] => Array ( [value] => 0.05 ) [6] => Array ( [value] => 0 ) [7] => Array ( [value] => 440 ) [8] => Array ( [value] => 230 ) [9] => Array ( [value] => 0.05 ) [10] => Array ( [value] => 0 ) [11] => Array ( [value] => 228 ) [12] => Array ( [value] => 12 ) ) 

So far so good :) But how can I now access the values of the json file? In other words how can I get the values - e.g. 12 or 94338.

Many thanks in advance.

CodePudding user response:

You can access the data you need with a basic foreach loop.

foreach ($json_array as $item) {
    // you have access to the value here
    echo $item['value'];
}

CodePudding user response:

$json_array[0], $json_array[1] 

etc. will give you the specific value

$colors = ["Red", "Green", "Blue"];

$colors[0] will give you "Red" $colors[1] will give you "Green"

if you have nested arrays like

$colors = [["Red"], ["Green", "Blue"]];


$colors[0] will give you ["Red"]
$colors[0][0] will give you "Red"
$colors[1] will give you ["Green", "Blue"]
$colors[1][0] will give you "Green"

Indexes can be string like in your example:

$colors = ["value" => ["Red"]];

$colors["value"] will give you ["Red"]
$colors["value"][0] will give you "Red"

If you want to loop over your array just use for or foreach loop

foreach ($json_array as $key => $value) {
    echo $key;
    echo $value;
}
  • Related