php - How to loop through json object, which has been converted to associative array, to get prop value
I am using PHP (I am a noob) to retrieve a file from the local server. This is a json file. I then convert this into an associative array. However I am having issues with looping through the properties and arrays, to target the value I need.
Below is what each element of the array looks like, and I trying to target the iso2 and name property/values of each country.
array (
'type' => 'FeatureCollection',
'features' =>
array (
0 =>
array (
'type' => 'Feature',
'properties' =>
array (
**'name' => 'Bahamas',
'iso_a2' => 'BS',**
'iso_a3' => 'BHS',
'iso_n3' => '044',
),
'geometry' =>
array (
'type' => 'MultiPolygon',
'coordinates' =>
array (
0 =>
array (
0 =>
array (
0 =>
array (
0 => -77.53466,
1 => 23.75975,
),
1 =>
array (
0 => -77.78,
1 => 23.71,
),
2 =>
array (
0 => -78.03405,
1 => 24.28615,
),
3 =>
array (
0 => -78.40848,
1 => 24.57564,
),
4 =>
array (
0 => -78.19087,
1 => 25.2103,
),
5 =>
array (
0 => -77.89,
1 => 25.17,
),
6 =>
array (
0 => -77.54,
1 => 24.34,
),
7 =>
array (
0 => -77.53466,
1 => 23.75975,
),
),
),
1 =>
array (
0 =>
array (
0 =>
array (
0 => -77.82,
1 => 26.58,
),
1 =>
array (
0 => -78.91,
1 => 26.42,
),
2 =>
array (
0 => -78.98,
1 => 26.79,
),
3 =>
array (
0 => -78.51,
1 => 26.87,
),
4 =>
array (
0 => -77.85,
1 => 26.84,
),
5 =>
array (
0 => -77.82,
1 => 26.58,
),
),
),
2 =>
array (
0 =>
array (
0 =>
array (
0 => -77,
1 => 26.59,
),
1 =>
array (
0 => -77.17255,
1 => 25.87918,
),
2 =>
array (
0 => -77.35641,
1 => 26.00735,
),
3 =>
array (
0 => -77.34,
1 => 26.53,
),
4 =>
array (
0 => -77.78802,
1 => 26.92516,
),
5 =>
array (
0 => -77.79,
1 => 27.04,
),
6 =>
array (
0 => -77,
1 => 26.59,
),
),
),
),
),
),
Here is how I am trying to access the array, but to no avail
forEach($assArr["features"] as $element){
if ($element[0]["properties"]["iso_a2"] == "BS"){
echo_r($element[0]);
}
}
What the page outputs "Undefined offset: 0"
Answer
Solution:
$element
will refer to the values inside already.
forEach($assArr["features"] as $element){
if ($element["properties"]["iso_a2"] == "BS"){
echo_r($element);
}
}
If you need the 0, you can do the following
forEach($assArr["features"] as $key => $element){
if ($element["properties"]["iso_a2"] == "BS"){
echo_r($key); // will be 0
echo_r($element);
}
}
Source