Currently seeking new career opportunities in web development, particularly with Laravel, Hire Me
Php Find And Replace Json

Introduction

Provide a JSON array and an array containing values to replace.

Create an instance of FindAndReplaceJson call replace and pass in the JSON array and array of replacing values.

JSON is returned with the replaced values. Keys can also be replaced by specifying named keys in $replaces array.

$payload = json_encode([
    'name'   => 'Joe Bloggs',
    'age'   => 23,
    'location' => 'London',
]);

//let's replace the values for age and location
$replaces = [
    'age' => 45, 
    'location' => "Manchester"
];

$runner = new FindAndReplaceJson();
return $runner->replace($payload, $replaces);

Result:

{
  "name": "Joe Bloggs",
  "age": "45",
  "location": "Manchester"
}

By default, JSON is expected but a normal array can be used by passing false as the third argument to FindAndReplaceJson. When the set to false FindAndReplaceJson expects an array and will return an array.

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.