Shiva's avatar
Level 5

Cannot update my json file index keys

I'm trying to run a artisan command but I'm having a bit of a problem trying to update my json file in my json file it looks like this

{
    "CL001": {
        "client_name": "Client 1",
        "client_email": "[email protected]",
    },
    "CL002": {
      "client_name": "Client 2",
      "client_email": "[email protected]",
    }
}

What I need to do is a bulk change on my client codes so for example CL001 needs to be PR001.

I've managed to isolate the codes but I'm having a bit of trouble trying to push the codes up so that they can change.

Here is my codes

$old_code = "CL001";
$new_code = "PR001";


$json = (array)json_decode(file_get_contents(storage_path('/Clients/clients.json')));

foreach($json as $key => $value)
{
  if(stripos($key, $old_code) !== false)
  {
     $newClientCode = str_replace($old_code, $new_code, $key);
  }
}

and that is where I get stuck. I'm not sure how to now go and update my json file with the new codes

0 likes
3 replies
automica's avatar

@shiva something like this?

$clients = (array)json_decode(file_get_contents(storage_path('/Clients/clients.json')));


$result = [];

foreach($client as $key => $value)
{

  $key = ($key === $old_code) ? $new_code : $key;

  $result[$key] = $value;

};

 
 // do something with $result

a note, I've renamed your $json variable as, at that point, its a normal array not json object.

if you want to do multiple, make an array of your old and new values and do the following

$swaps[
	'CL001' => 'PR001',
	'CL002' => 'PR002'
];


$clients = (array)json_decode(file_get_contents(storage_path('/Clients/clients.json')));

$result = [];

foreach($clients as $key => $value)
{

  $key = isset($swaps[$key]) ? $swaps[$key] : $key;

  $result[$key] = $value;

};

 
 // do something with $result

Shiva's avatar
Level 5

I tried that but my keys never changed

automica's avatar

@shiva where haven't they changed? in your app? Can you show how you are calling this as an artisan command.

if you are rewriting a file that is loaded in as part of your config settings, you'll need to clear your config cache after

php artisan config:clear

Please or to participate in this conversation.