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?
1 Answer 1
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
if
statement is entered? Are errors on?