Reputation: 115
I use a library for Synchronize a local WebSQL DB to a server specifically https://github.com/orbitaloop/WebSqlSync. I use PHP: 5.4.7 this is json var $json
{
"info":"",
"data":{
"clientes":[],
"conceptos_gastos":[],
"formaspago":[{
"idFormaPago":7,
"FormaPago":"quwuw",
"Dias":1,
"Cuotas":1,
"last_sync_date":null
}],
"listaprecios":[],
"producto":[],
"repartidores":[],
"tipodocumento":[],
"vehiculos":[],
"zonas":[]
}
}
when I try to get the values
$js=json_decode($json,true);
foreach ($js['formaspago'] as $row ) {
echo $row["Formapago"];
}
I get this error:
Invalid argument supplied for foreach
any help is appreciated
Upvotes: 1
Views: 406
Reputation: 4616
use json_decode
//array
$data = json_decode($json, true);
foreach($data["data"]["formaspago"] as $row) {
echo $row["Formapago"];
}
Thanks @JimL for the hint.
Upvotes: 2
Reputation: 5016
You're not passing a valid array to the foreach
loop. However, even if you parse the json you've supplied, a foreach
won't work because it's an object not an array.
$json = '{
"info":"",
"data":{
"clientes":[],
"conceptos_gastos":[],
"formaspago":[{
"idFormaPago":7,
"FormaPago":"quwuw",
"Dias":1,
"Cuotas":1,
"last_sync_date":null
}],
"listaprecios":[],
"producto":[],
"repartidores":[],
"tipodocumento":[],
"vehiculos":[],
"zonas":[]
}
}';
$obj = json_decode($json);
print $obj->info
will return an empty string.
$obj->data
is an object that has various properties some of which are empty arrays. Passing these into the foreach
should work. i.e.
foreach($obj->data->clients as client) {
// Do something here
}
Further, $obj->data->formaspago
has exactly one element in the array, which is an object. You can access this object with a foreach
loop:
foreach($obj->data->formaspago as formaspago) {
print formaspago->idFormaPago; // Will print 7
print formaspago->FormaPago; // Will print "quwuw"
print formaspago->Dias; // Will print 1
print formaspago->Cuotas; // Will print 1
print formaspago->last_sync_date; // Will print nothing
}
Upvotes: 1