Ranjit T
Ranjit T

Reputation: 53

Add Text to a particular element in JSON array with PHP

I want add extra text to a particular element in array, from below INPUT, I want to change "Image":"12001116" to "Image":"wp-content/upload/12001116.jpg".

So I want add "wp-content/upload/" $value['Image']; ".jpg" Could someone please, Help!

INPUT

$json = '[
{
"Image":"12001116",
"Name":"Jean-Marc",
"CODE_POSTAL":"12630 ",
"VIL":"AGEN D AVEYRON",
"LATITUDE":"44.343518",
"LONGITUDE":"2.716004"
},
{
"Image":"1200558",
"Name":"Aurélien ",
"CODE_POSTAL":"12630 ",
"VIL":"AGEN D AVEYRON",
"LATITUDE":"42.343828",
"LONGITUDE":"2.920056"
}
]';

and OUTPUT should be

$json = '[
{
"Image":"wp-content/upload/12001116.jpg",
"Name":"Jean-Marc",
"CODE_POSTAL":"12630 ",
"VIL":"AGEN D AVEYRON",
"LATITUDE":"44.343518",
"LONGITUDE":"2.716004"
},
{
"Image":"wp-content/upload/1200558.jpg",
"Name":"Aurélien ",
"CODE_POSTAL":"12630 ",
"VIL":"AGEN D AVEYRON",
"LATITUDE":"42.343828",
"LONGITUDE":"2.920056"
}
]';

Upvotes: 1

Views: 293

Answers (1)

Ar Rakin
Ar Rakin

Reputation: 542

You can use array_map() to loop over the objects:

$json = json_decode($input); // $input is the JSON input string
$newJson = array_map(function ($obj) {
      $obj->Image = 'wp-content/upload/' . $obj->Image . '.jpg';
      return $obj;
}, $json);
$output = json_encode($newJson, JSON_PRETTY_PRINT);
echo $output; // done!

EDIT: If you don't want backslashes \, then change line 6 to:

$output = json_encode($newJson, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

Upvotes: 1

Related Questions