I need to update the property accessories
of this JSON
JavaScript
x
{
id: "1",
name: "TEST",
accessories: [
"1",
"2",
"3"
]
}
How can I add 4
or change 3
to 4
to the accessories
array?
Advertisement
Answer
JavaScript
//Decode JSON to PHP object
$arrr = json_decode('{
"id": "1",
"name": "TEST",
"accessories": [
1,
2,
3
]
}');
$old_value = 3; // The value you want to change
$new_value1 = 4; // The value you want to change it to
$new_value2 = 100; // A new value you want to insert into the array
$array_key = array_search($old_value, $arrr->accessories); // Get array key of old value
$arrr->accessories[$array_key] = $new_value1; // Update array with value
$arrr->accessories[] = $new_value2; // Add extra value to array
echo json_encode($arrr); // Re-encode and print results
// Output: {"id":"1","name":"TEST","accessories":[1,2,4,100]}