how to retrieve json response objects which stores values inside nested arrays in php

897

I've json object with key named geometry,the geometry key stores array called path & the path stores multidimensional array

I tried to loop through paths but loops returns only the first index values

$result = curl_exec($ch);
foreach($JsonData->features as $chunk )
{
    $geo =$chunk->geometry->paths;
    echo $geo;
}

expected result - is to store the paths values into one variable. actual result - returning only one value.

The data is...

"geometry": { "paths": [ [ [ -9131174.97888261, 3120622.68129019 ], 
    [ -9131167.41739487, 3120625.21649344 ], 
    [ -9131007.49336538, 3120782.33590721 ], 
    [ -9130998.82313552, 3120791.07506482 ] ] ] }
93

Answer

Solution:

The following code should get you back on track:

<?php
$json = '{ "paths": [ [ [ -9131174.97888261, 3120622.68129019 ], [ -9131167.41739487, 3120625.21649344 ], [ -9131007.49336538, 3120782.33590721 ], [ -9130998.82313552, 3120791.07506482 ] ] ] }';
$object = json_decode($json);

foreach($object->paths[0] as $path) {
    $geo = $path;
    echo $geo[0];
    echo $geo[1];
}
250

Answer

Solution:

As you keep on overwriting the value in$geo you will only get 1 value. You should build an array (adding each value using[]) and that should give you all of the results. You may also need to adjust the way you access the data, I've updated the loop to$JsonData->features->geometry->paths[0]...

$geo = [];
foreach($JsonData->features->geometry->paths[0] as $chunk )
{
    $geo[] =$chunk;
}
print_r($geo);

which results in something like...

Array
(
    [0] => Array
        (
            [0] => -9131174.9788826
            [1] => 3120622.6812902
        )

    [1] => Array
        (
            [0] => -9131167.4173949
            [1] => 3120625.2164934
        )

    [2] => Array
        (
            [0] => -9131007.4933654
            [1] => 3120782.3359072
        )

    [3] => Array
        (
            [0] => -9130998.8231355
            [1] => 3120791.0750648
        )

)

People are also looking for solutions to the problem: php - How to use array push in laravel

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.