I have an array mind
[{"id":"331","file_name":"3b1379e2496408dd4c865f5f63f96bf6","file_path":"https://path/3b1379e2496408dd4c865f5f63f96bf6.png"},
{"id":"332","file_name":"d0ef559473a061086592bceed0880a01","file_path":"https://path/d0ef559473a061086592bceed0880a01.png"}]
I need to output this array so that in the end it looks like this
[{url:"https://path/3b1379e2496408dd4c865f5f63f96bf6.png"},
{url:"https://path/d0ef559473a061086592bceed0880a01.png"}]
To output only one field from an array, I use
array_column($array, 'file_path')
And I end up with
["https://path/3b1379e2496408dd4c865f5f63f96bf6.png",
"https://path/d0ef559473a061086592bceed0880a01.png"]
But how now to make these fields be objects and add a url in front of them?
2
Answers
Here’s a dirt-basic version – simply loop through the array and make a new one with just the property you want in each entry:
Demo: https://3v4l.org/JcKZE
Or for a slick one-liner, make use of the
array_map
function:In the above, replace the
$output = [];
and theforeach
loop with:Demo: https://3v4l.org/a10kB
You can use a mapping operation:
https://3v4l.org/vbguH
For 7.3 and below (no arrow function support):
Note, unless you want object syntax or features in PHP (
$foo->url
), you can omit the(object)
casting; it will still JSON encode with object syntax unless you tell it not to.