1

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"
}
]';

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

11 Comments

Missing extensions when concatenating. Please check your results.
@RanjitT please give specifics rather than 'some error'. The above code works for me (minus jpg extensions). Is $input assigned/equal to your JSON string?
@ArRakin , thank you so much you are a life saver. Its now showing "wp-content\/upload\/12001116.jpg" is it possible to make every \/ to just / because this is to load the image the server... but with this "\/" its not loading. Thanks again
@ArRakin My goodness! It worked like a charm. Thank you so much. you too have a great day!
@ArRakin Sorry to interrupt you again. if possible. could you please have a look at this. stackoverflow.com/questions/70948560/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.