B
B
Bokovlad2020-03-07 11:44:22
PHP
Bokovlad, 2020-03-07 11:44:22

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);

I get:
[
    {
        "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
        }
    }]

I want to find an object in the foreach file that contains a specific id_project and add new data to teem in it so that in the end it turns out:
{
  "id_project": "204",
  "name": "Егор",
  "phone_sto": "+79991234567",
  "teem": [{
      "names": "Коля",
      "olg": 25
    },
    {
      "names": "Вася",
      "olg": 30
    }
  ]
}

Those. add new team members to teem.

I wrote such a solution, but I don’t know what needs to be specified in the loop so that the value is written to a specific project_id project.
$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

I tried in different ways, but it turns out that the entire Json file is completely overwritten and only what I specified in the loop remains, while all other data is erased.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2020-03-07
@Bokovlad

$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 question

Ask a Question

731 491 924 answers to any question