Reputation: 377
new to php.... can't seem to get the contents of this array... ie. trying to do: $key = var0 and $value = string0
This is what I am trying the following, with no success:
$getJSON = [
{
"item0": [
{"var0":"string0"},
{"var1":"string1"},
{"var2":"string2"},
{"var3":"string3"}
]
}
]
$arr = json_decode( $getJSON, true );
$test1 = $arr[0]['item0']['var0'];
$test2 = $arr['item0']['var0'];
Upvotes: 0
Views: 51
Reputation: 2432
First change Desing of json pattern
$getJSON = '{"item0":[
{"var0":"string0"},
{"var1":"string1"},
{"var2":"string2"},
{"var3":"string3"}
]
}';
use json_decode function for get json data
$arr = json_decode( $getJSON);
echo $arr->item0[0]->var0.'</br>';
echo $arr->item0[1]->var1.'</br>';
echo $arr->item0[2]->var2.'</br>';
echo $arr->item0[3]->var3.'</br>';
Upvotes: 0
Reputation: 780724
The argument to json_decode()
has to be a string, not an array. So put it in quotes.
$getJSON = '[
{
"item0": [
{"var0":"string0"},
{"var1":"string1"},
{"var2":"string2"},
{"var3":"string3"}
]
}
]';
After you decode, $arr[0]['item0']
contains an array, so to get the var0
element it would be $arr[0]['item0'][0]['var0']
.
Having an array of separate objects, each with different keys, is probably not a great design. It would be better if the you did it like this:
$getJSON = '{
"item0": {
"var0":"string0",
"var1":"string1",
"var2":"string2",
"var3":"string3"
}
}'
Then the value you want would be:
$arr['item0']['var0']
Upvotes: 1
Reputation: 21600
First of all fix your json part:
$json = '{
"item0": [
{"var0": "string0"},
{"var1": "string1"},
{"var2": "string2"},
{"var3": "string3"}
]
}';
Now if you var_dump the json_decoded content with
json_decode($json, JSON_PRETTY_PRINT);
you will obtain
array(1) {
'item0' =>
array(4) {
[0] =>
array(1) {
'var0' =>
string(7) "string0"
}
[1] =>
array(1) {
'var1' =>
string(7) "string1"
}
[2] =>
array(1) {
'var2' =>
string(7) "string2"
}
[3] =>
array(1) {
'var3' =>
string(7) "string3"
}
}
}
This means that you can get values with:
$decoded = json_decode($json, true);
var_dump($decoded['item0'][0]['var0']);
Upvotes: 1