$val_array = json_decode($json_data, true);
I decoded a JSON array & stored it into a variable. JSON has data from server side.
When I var dump this array var_dump($val_array); I get:
{
"groups": {
"connect": "yes",
"Name": "admin",
"id": "1",
"Groups": "1",
"manage": "1",
"Users": "1",
"show": "1",
"log": "1"
}
}
And I check size of array.
$x=count($val_array); gives 1 as output
$x=count($val_array['groups']); gives 8 as output
And when I have more data in my database, JSON looks like this
{
"groups": [{
"connect": "yes",
"Name": "admin",
"id": "1",
"Groups": "1",
"manage": "1",
"Users": "1",
"show": "1",
"log": "1"
},
{
"connect": "no",
"Name": "noadmin",
"id": "2",
"Groups": "2",
"manage": "2",
"Users": "2",
"show": "2",
"log": "2"
}
] }
I want to show the values to an html table. I use a simple for loop.
$val_array = $val_array['groups'];
for($i=0; $i<$x; $i++)
{
$a= $val_array['connect'];
$b= $val_array['Name'];
$c= $val_array['id'];
$d= $val_array['Groups'];
$e= $val_array['manage'];
$f= $val_array['Users'];
$g= $val_array['show'];
$h= $val_array['log'];
}
What is the value of $x that I should use?
When I use $x=count($val_array); and if JSON has more than 1 data, error comes up. Undefined offset or something, if data is only 1, then it works.
When I use this $x=count($val_array['groups']); and if JSON data has 1 data, size is returned as 8.
When I used
$x=count($val_array['groups']);
and
var_dump($val_array);
I got: Notice: Undefined offset: 0 in my page
Size as 8.
array (size=1)
'groups' =>
array (size=8)
'connect' => string '1' (length=1)
'Name' => string 'admin' (length=10)
'id' => string '1' (length=1)
'Groups' => string '1' (length=1)
'manage' => string '1' (length=1)
'Users' => string '1' (length=1)
'show' => string '1' (length=1)
'log' => string '1' (length=1)
as var_dump output.
}after groupsvar_dump($val_array);for second json string just after decoding it.foreachinstead offor.var_dump()display associative arrays like that? It always puts the type of the data first, and shows arrays withArray(size)at the beginning, and=>between the keys and values, not:. That looks more like the original JSON than the output ofvar_dump.{ }surrounds objects, every element has to be in the formkey: value. You have no key for the second value. Are you sure it isn'tgroups: [ { ... }, { ...} ]?