我目前正在採取json對象並將其轉換爲用於數據庫存儲的php數組。它最初是在工作,但由於某種原因或改變,現在突然停止工作。 $data
擁有json對象。然後我使用json_decode
進行轉換。它什麼也不返回,換句話說它不是一個數組。我如何正確地將json對象轉換爲php數組? DEMO對PHP數組的JSON對象 - 無效數組
if(isset($_POST['submit'])) {
$data = stripslashes($_POST['data']);
$personArray = json_decode($data, true);
print_r($personArray);
if (is_array($personArray))
{
foreach($personArray as $key => $value){
$person_id = $value['personID'];
$main1 = ($value['main1'] == "true") ? 1 : 0;
$main2 = ($value['main2'] == "true") ? 1 : 0;
$person_fname = $value['firstName'];
$person_lname = $value['lastName'];
$person_phone = $value['person_phone'];
$person_phone_alt = $value['person_phone_alt'];
$person_status = "ACTIVE";
$query_init2 = "INSERT INTO person (main1, main2, first_name, last_name, person_phone, person_phone_alt) VALUES (:main1, :main2, :first_name, :last_name, :person_phone, :person_phone_alt) ON DUPLICATE KEY UPDATE main1=:main12, main2=:main22, first_name=:first_name2, last_name=:last_name2, person_phone=:person_phone2, person_phone_alt=:person_phone_alt2";
$query_prep2 = $db_con->prepare($query_init2);
$insert_result2 = $query_prep2->execute(array(
":person_id" => $person_id,
":main1" => $main1,
":main2" => $main2,
":first_name" => $person_fname,
":last_name" => $person_lname,
":person_phone" => $person_phone,
":person_phone_alt" => $person_phone_alt,
":main12" => $main1,
":main22" => $main2,
":first_name2" => $person_fname,
":last_name2" => $person_lname,
":person_phone2" => $person_phone,
":person_phone_alt2" => $person_phone_alt
));
}
}else{
echo "Not an array";
}
}
HTML
<textarea name="data">
[
{
"firstName": "Danny",
"lastName": "LaRusso",
"ciscoID": "123",
"email": "[email protected]",
"phone": "(555) 121-2121",
"fax": "(123) 123-4567",
"contact_role": true,
"netacadContact": true,
"netacadStaff": false,
"netacadSuccess": false,
"instructor_role": false
},
{
"firstName": "Sensei",
"lastName": "Miyagi",
"ciscoID": "456",
"email": "[email protected]",
"phone": "(555) 444-2222",
"fax": "(123) 123-4567",
"contact_role": false,
"netacadContact": false,
"netacadStaff": false,
"netacadSuccess": false,
"instructor_role": true
}
]
</textarea>
這個作品完美! –