Home > Net >  split the array into objects and add a description
split the array into objects and add a description

Time:01-13

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?

CodePudding user response:

You can use a mapping operation:

array_map(
    fn($value) => (object) ['url' => $value],
    array_column($array, 'file_path')
)

https://3v4l.org/vbguH

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.

CodePudding user response:

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:

$json = '[{"id":"331","file_name":"3b1379e2496408dd4c865f5f63f96bf6","file_path":"https://path/3b1379e2496408dd4c865f5f63f96bf6.png"},
{"id":"332","file_name":"d0ef559473a061086592bceed0880a01","file_path":"https://path/d0ef559473a061086592bceed0880a01.png"}]';

$arr = json_decode($json, true);
$output = [];

foreach ($arr as $item)
{
    $output[] = ["url" => $item["file_path"]];
}

echo json_encode($output);

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 the foreach loop with:

$output = array_map(fn($value) => (object) ['url' => $value], array_column($arr, 'file_path'));

Demo: https://3v4l.org/a10kB

  •  Tags:  
  • php
  • Related