Answer the question
In order to leave comments, you need to log in
How to update array from json in php?
Greetings! Tell me how to update the array correctly. I add data like this:
$name = "Василий";
$phone = '+798522141';
$name2 = 'Иван';
$old = 25;
$file = file_get_contents('new.json');
$taskList = json_decode($file);
$id_count = count ($taskList)+1;
$id_count_total = "20".$id_count;
unset($file);
$taskList[] = array(
'id_project'=>$id_count_total,
'name'=>$name,
'phone_sto'=>$phone,
'teem'=>array(
'names'=>$name2,
'olg'=>$old
)
);
$datas = json_encode($taskList, JSON_PRETTY_PRINT);
file_put_contents('new.json', $datas);
unset($taskList);
[
{
"id_project": "201",
"name": "\u0412\u0430\u0441\u0438\u043b\u0438\u0439",
"phone_sto": "+798522141",
"teem": {
"names": "\u0418\u0432\u0430\u043d",
"olg": 25
}
},
{
"id_project": "202",
"name": "\u0412\u0430\u0441\u0438\u043b\u0438\u0439",
"phone_sto": "+798522141",
"teem": {
"names": "\u0418\u0432\u0430\u043d",
"olg": 25
}
}]
{
"id_project": "204",
"name": "Егор",
"phone_sto": "+79991234567",
"teem": [{
"names": "Коля",
"olg": 25
},
{
"names": "Вася",
"olg": 30
}
]
}
$file = file_get_contents('new.json');
$taskList=json_decode($file);
foreach ( $taskList as $key){
if ($key->id_project == '202' ) {
$newdatas[] = ??????
} }
file_put_contents('new.json',json_encode($newdatas, JSON_PRETTY_PRINT));
unset($taskList); // Очистить переменную $taskList
Answer the question
In order to leave comments, you need to log in
$file = file_get_contents('new.json');
$newData =
$taskList=json_decode($file);
foreach ( $taskList as $key){
if ($key->id_project == '202' ) {
$key->team[] = $newData;
}
}
file_put_contents('new.json',json_encode($taskList, JSON_PRETTY_PRINT));
unset($taskList);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question