0

I am trying to parse the following json in php:

[{"id":"firstname","optionValue":""},{"id":"lastname","optionValue":""},{"id":"","optionValue":"Submit"}]

Im getting the string sent to me with a get request

This is what i got so far:

if(isset($_GET['data'])) {
 $json_a = json_decode($_GET['data'], true);
 foreach ($json_a as $a => $b) {
 echo $a;
 }
}

However echo $a; does not output anything.

Any ideas?

asked Nov 7, 2013 at 18:03
3
  • How are you sending it? Did you inspect the request? Did you make sure the if statement is entered? Are errors on? Commented Nov 7, 2013 at 18:06
  • The way you have it there right now, you should be seeing the indexes outputted. $b should contain the "lastname" and "optionValue" data. Commented Nov 7, 2013 at 18:08
  • I want to get firstname -> value lastname -> value Commented Nov 7, 2013 at 18:09

1 Answer 1

2

First of all, make sure you have the JSON string decoded properly by doing a var_dump($json_a);. If the JSON is not valid, json_decode() will return NULL and you won't be able to get the contents.

If you can verify that json_decode() is returning an array containing the required information, keep reading.

You have the following in your code:

foreach ($json_a as $a => $b) {
 echo $a;
}

This will just print out the keys: 0, 1, 2. You want the value instead. For that, your loop needs to look like below:

foreach ($json_a as $value) {
 echo $value['id'].PHP_EOL;
}

This will now print out:

firstname
lastname

Demo!

answered Nov 7, 2013 at 18:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.