Skip to content
Advertisement

Reassign value from json key/value pair to next key

I got a json file which looks like the following (Showing one out of several rows that looks the same):

 "description 1": {
  "year0": "49",
  "year1": "48",
  "year2": "876786",
  "year3": "1234"
},

Using PHP, I need to move each value down so value for year0 becomes the value for year1 and so on (value for year 3 will be removed and year0 will be empty like this:

 "description 1": {
  "year0": "",
  "year1": "49",
  "year2": "48",
  "year3": "876786"
},

Is there any faster way to process the data than looping through each key value, saving it to a variable and assigning it to the next key and so on?

Advertisement

Answer

There is no approach to do this faster, but i think there is a simple and readable approach, i think the best way to go about it is the collection method mapWithKeys(). It allows you to do an array map, but changing the key in the process. This will be easier in my opinion, instead of thinking of moving each variable down one place, just add one year to the key and remember to add the first year to the new array.

$years = collect(json_decode('json')->description_1);

$firstYear = null;

$years = $years->mapWithKeys(function ($value, $key) use (&$firstYear) {
    if (! $firstYear) {
        $firstYear = $key;
    }

    $year = intval(Str::after('year', $key)) + 1;

    return ['year' . $year => $value];
})->all();

$years[$firstYear] = '';
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement