2

I know there are similar questions all over Stackoverflow, but I did not find any help for the problem I'm having.

I have this JSON:

[{ "name": "Name0", "services": [ [{ "Service": "Service00", "Description": "Desc00" }, { "Service": "Service01", "Description": "Desc01" }] ] }, { "name": "Name1", "services": [ [{ "Service": "Service10", "Description": "Desc10" }] ] }] 

I loop through it with:

$quoteJson = json_decode($quoteJson); foreach($quoteJson as $mydata) { echo $mydata->name . "<br>"; foreach($mydata->services as $key => $value) { echo $value[$key]->Service . "<br>"; echo $value[$key]->Description . "<br>"; } } 

And the result I get is:

Name0 Service00 Desc00 Name1 Service10 Desc10 

I am not able to loop through the service elements, to get:

Name0 Service00 Desc00 Service01 Desc01 Name1 Service10 Desc10 

    3 Answers 3

    3

    For some reason, services is an array in an array. Made a small change to your code:

    foreach($quoteJson as $mydata) { echo $mydata->name . "<br>"; foreach($mydata->services[0] as $key => $value) { echo $value->Service . "<br>"; echo $value->Description . "<br>"; } } 

    And now it it returns:

    Name0
    Service00
    Desc00
    Service01
    Desc01
    Name1
    Service10
    Desc10

    2
    • Worked like a charm! Thanks! Will make some resaerch as I don't understand why [0] index is needed.
      – anexo
      CommentedJun 13, 2017 at 16:55
    • Currently your services object contains a nested array. Essentially: "services": [ [ ] ]. You use the [0] to access the first, and only element in services, which contains the data you're trying to reach.
      – Hollings
      CommentedJun 13, 2017 at 16:59
    1

    Since $mydata->services is multi dimensional array, you need to loop $value variable.

    $quoteJson = json_decode($quoteJson); foreach($quoteJson as $mydata) { echo $mydata->name . "\n"; foreach($mydata->services as $key => $value) { foreach($value as $k=>$v){ // loop the array echo $v->Service . "\n"; echo $v->Description . "\n"; } } } 
      1

      The output is not as expected because you have missed an inner loop. the code below works fine.

      foreach($quoteJson as $mydata) { echo $mydata->name . "<br>"; foreach($mydata->services as $key => $value) { foreach($value as $innerdata){ echo $innerdata->Service . "<br>"; echo $innerdata->Description . "<br>"; } } 

      }

        Start asking to get answers

        Find the answer to your question by asking.

        Ask question

        Explore related questions

        See similar questions with these tags.