Rizki Wahyu Rizki Wahyu - 26 days ago 6
PHP Question

JSON Array to PHP Array Multidimensional

i have json data like this :

{
"response": {
"count": 212,
"list": [
{
"code": "02007",
"name": "swept the room",
"rate": 750000,
"withValue": false
},
{
"code": "02005",
"name": "mop room",
"rate": 600000,
"withValue": false
},
{
"code": "02003",
"name": "buying food",
"rate": 175000,
"withValue": false
}
]
},
"metaData": {
"message": "OK",
"code": 200
}
}


and i have table schema like this :


mysql> desc master_service;

+----------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+----------------+
| id | int(25) | NO | PRI | NULL | auto_increment |
| code | varchar(10) | YES | | NULL | |
| name | varchar(20) | YES | | NULL | |
| rate | double | YES | | NULL | |
| withvalue | tinyint(1) | YES | | NULL | |
+----------------+-------------+------+-----+---------+----------------+



and my coding like this.

//using php pdo

include_once 'db_connect.php';
$data = json_decode($response, true);

$tempservice = array();
if(isset($data['response']) && isset($data['response']['list']))
{
//use foreach on ['response']['list'] index - here are teachers data stored
foreach($data['response']['list'] as $service)
$tempservice[$kesadaran['code']] = $service['name'];
}

foreach($tempservice as $key =>$value) {
$sql = "insert into master_service(code,name) Values ('$key','$value')";
$st = $dbh->prepare($sql);
$st->execute ($data);
}


it can only save the database in the form of codes and names. i want rate and withValue can be save on database

Answer
foreach($data['response']['list'] as $value) {
    $sql = "insert into master_service(code,name,rate,withvalue) Values ('{$value['code']}','{$value['name']}', '{$value['rate']}', '{$value['withValue']}')";
    $st = $dbh->prepare($sql);
    $st->execute ($data);
}

sorry i forgot the true parameter on json_decode.. edited