Evan Lemmons
Evan Lemmons

Reputation: 807

Need to apply a function to update a specific property of an array

I've got an array of clients coming in from an API and I need to format their "logo" in the controller before it hits the view. When I use array_map it's returning an array of just the formatted logos, but I need it to return the entire array with just the logo property for each entry being formatted.

It seems array_map and array_walk both return an array of only what has been formatted, but is there a function or some combination of functions that would return the original array with just updated values for a specific property?

Here's my current code, just basic array_map syntax. clients_array is an array of arrays that have a bunch of properties like name, location, logo, etc.:

    $clients_array = $this->clients->getClients();
    $clients_array = array_map(function ($logo) {
      return cloudfront_asset($logo->logo_thumbnail);
    }, $clients_array);

Upvotes: 0

Views: 52

Answers (1)

patricus
patricus

Reputation: 62268

You control the output of array_map, so instead of just returning the formatted logo, update your $logo object and return that.

$clients_array = $this->clients->getClients();
$clients_array = array_map(function ($logo) {
    $logo->logo_thumbnail_formatted = cloudfront_asset($logo->logo_thumbnail);
    return $logo;
}, $clients_array);

Upvotes: 2

Related Questions