1

I have this json object and i need to iterate each text and value keys, please can somebody help me on this?

I've tried in too many ways but no success next to the json is my last try

Thanks in advance

[
    {
        "term": [
            {
                "text": "36",
                "value": "36"
            },
            {
                "text": "48",
                "value": "48"
            },
            {
                "text": "60",
                "value": "60"
            },
            {
                "text": "72",
                "value": "72"
            },
            {
                "text": "84",
                "value": "84"
            },
            {
                "text": "96",
                "value": "96"
            },
            {
                "text": "120",
                "value": "120"
            }
        ]
    }
]

I'm trying this way but no success

foreach($Terms['term'] as $key=>$val){ 
    echo $key;
}
4
  • 1
    Can you add the code where you create the $Terms array? Commented Mar 28, 2014 at 21:01
  • You have an array wrapping an object wrapping an array... Commented Mar 28, 2014 at 21:02
  • [code] $optionsXML = simplexml_load_file("js/SelectParams.xml"); $Terms = $optionsXML->xpath("//ProductBase[@Id=".$ProductData->ProductBaseId."]/terms"); $Terms = json_encode($Terms); [/code] Commented Mar 28, 2014 at 21:06
  • @martinezjc: [code] tags don't work in comments (or anywhere on SO). Please edit the original question to add more information. Commented Mar 28, 2014 at 21:09

1 Answer 1

3

You need to decode JSON into array (or object), only then you can access it's elements.

$data = json_decode($jsonString, true);
// according to your data, you have an array inside object, which is inside another array.
foreach ($data[0]['term'] as $key => $value) {
}
Sign up to request clarification or add additional context in comments.

2 Comments

I made this json_decode($Terms, true); Now im getting this error Undefined offset: 0
Forget about it i remove the extra zero index and now is working like a charm, thanks!!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.