我正在尝试写入对象内的变量,但我找不到如何做到这一点。
Array
(
[0] => stdClass Object
(
[id] => 3
[rota_name] => Tea and coffee
[rota_owner_name] => 9
[rota_notes] =>
[rota_entry] => {"rota_entry0":{"person":"8","rota_assignment_date":"2018-04-01 20:17:48","rota_role":""},"rota_entry1":{"person":"7","rota_assignment_date":"2018-04-08 20:17:48","rota_role":""},"rota_entry2":{"person":"11","rota_assignment_date":"2018-04-15 20:17:48","rota_role":""},"rota_entry3":{"person":"7","rota_assignment_date":"2018-04-22 20:17:48","rota_role":""},"rota_entry4":{"person":"10","rota_assignment_date":"2018-04-29 20:17:48","rota_role":""},"rota_entry5":{"person":"3","rota_assignment_date":"2018-05-06 20:18:20","rota_role":""},"rota_entry6":{"person":"11","rota_assignment_date":"2018-05-13 20:18:23","rota_role":""}}
[rota_advance_email_days] =>
[rota_reminder_sent] =>
)
我想将8人改为9人
所以我认为我需要获得rota_entry(使用foreach),然后使用Json_decode获取一个数组,然后我的大脑现在会受伤:(我不知道如何将其重置为数据库再次。
我可以找到许多谈论简单的JSON解码或简单的数组解析,但没有什么可以帮助解决这个问题
答案 0 :(得分:-1)
此代码假设$ obj =您显示的数组中的第一个条目。
所以$ obj = Array [0]
$json = json_decode($obj->rota_entry);
$json->rota_entry0->person = 9;
$obj->rota_entry = json_encode($json);
此代码将rota_entry0 person 8更改为
答案 1 :(得分:-1)
// Your original array
$array = [
0 => (object) [
'id' => 3,
'rota_name' => 'Tea and coffee',
'rota_owner_name' => 9,
'rota_notes' => '',
'rota_entry' =>' {"rota_entry0":{"person":"8","rota_assignment_date":"2018-04-01 20:17:48","rota_role":""},"rota_entry1":{"person":"7","rota_assignment_date":"2018-04-08 20:17:48","rota_role":""},"rota_entry2":{"person":"11","rota_assignment_date":"2018-04-15 20:17:48","rota_role":""},"rota_entry3":{"person":"7","rota_assignment_date":"2018-04-22 20:17:48","rota_role":""},"rota_entry4":{"person":"10","rota_assignment_date":"2018-04-29 20:17:48","rota_role":""},"rota_entry5":{"person":"3","rota_assignment_date":"2018-05-06 20:18:20","rota_role":""},"rota_entry6":{"person":"11","rota_assignment_date":"2018-05-13 20:18:23","rota_role":""}}',
'rota_advance_email_days' => '',
'rota_reminder_sent' => '',
]
];
// Create an empty object to replace the rota_entry key in the array
$rotaEntry = (object) [];
// Iterate through the original rota_entry and replace "person"
foreach (json_decode($array[0]->rota_entry) as $key => $value) {
// You can set whatever logic you want here
// For example: if ($key == "rota_entry4") {$value->person = 4;}
// I'm hardcoding "9"
$value->person = 9;
$rotaEntry->$key = $value;
}
// Assign the newly created (and modified) rotaEntry back to the original array
$array[0]->rota_entry = $rotaEntry;
答案 2 :(得分:-1)
试试这个:
$array = (array) $object;
foreach($array as &$value){
$json = json_encode($value['rota_entry']);
$json -> rota_entry0 -> person = 9;
$value['rota_entry'] = json_encode($json);
}
$array = (object) $array;
祝你好运。