Search code examples
phparraysobjectmultidimensional-arrayfiltering

Reduce objects in a 2d array to a single property and assign new static keys


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?


Solution

  • 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