V
V
vladislav9972020-05-25 15:10:53
PHP
vladislav997, 2020-05-25 15:10:53

How to update JSON using php?

Can you tell me how to update JSON using php? Let's say there are 100 entries, example:

json

[
{
"id": 1000,
"date": "2020-07-22 18:57:51",
"customer": "Hilary Greer",
},
{
"id": 1001,
"date": "2020-04-19 03:39:30",
"customer": "Yen Ortega",
},
{
"id": 1002,
"date": "2019-07-03 15:44:11",
"customer": "Maris Oconnor",
},
........
]


And, for example, you need to change the value of customer in the 1002 ID. How to do it?

I try this, it doesn't work
$jsonOrders = file_get_contents('templates/api/index.html.twig'); 
        $orders = json_decode($jsonOrders); 
        foreach($orders as $order)
        {
            if($order->id == 1002)
            {
                $order->customer = 'updated';
            }
        }

        file_put_contents('templates/api/index.html.twig', json_encode($orders)); // Перекодировать в формат и записать в файл.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
vladislav997, 2020-05-25
@vladislav997

$jsonOrders = file_get_contents('templates/api/index.html.twig');
        $orders = json_decode($jsonOrders); //,TRUE

        foreach($orders as $order)
        {
            if($order->id == 1002)
            {
                $order->status = 'cancelled';
            }
        }
        file_put_contents('templates/api/index.html.twig', json_encode($orders));

N
ninja op op, 2020-05-25
@kur4chyt

$jsonOrders = file_get_contents('orders.json');
$items = json_decode($jsonOrders,true);

$items2 = array();

foreach($items as $item) {
   if($item['id'] == '1002')
       $item['customer'] = 'value';
      array_push($items2, $item);
}
file_put_contents('orders.json', json_encode($items2));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question