CSS_Wizard CSS_Wizard - 4 months ago 27
PHP Question

How to update values in associative array using php foreach loop when key includes a specific string?

I need to change all the values for a matching key within an associative array using php but I can only target the key by matching a specific string within the key and not the entire key name as it may change.

In the case below, I need a way to target all the "_file" keys and change their filenames to a related attachment ID but targeting the entire key "bg_infographic_file" won't be possible as the key may change to "bg_whitepaper_file" or some other name.

Current $resources array:

Array
(
[0] => Array
(
[bg_infographic_title] => Logo Upload
[bg_infographic_file] => logomark-large-forVector.png
)

[1] => Array
(
[bg_infographic_title] => Profile Image
[bg_infographic_file] => ProfilePic.jpg
)

[2] => Array
(
[bg_infographic_title] => Document Upload
[bg_infographic_file] => Test_PDF.pdf
)

)


What I need as a result:

Array
(
[0] => Array
(
[bg_infographic_title] => Logo Upload
[bg_infographic_file] => 86390
)

[1] => Array
(
[bg_infographic_title] => Profile Image
[bg_infographic_file] => 99350
)

[2] => Array
(
[bg_infographic_title] => Document Upload
[bg_infographic_file] => 67902
)

)


I'm thinking of something along these lines but I can't quite figure it out as the following simply returns the unchanged array data:

foreach( $resources as $key=>$value ) {
if( strpos($key, '_file') !== FALSE ) {
$value = get_image_id_from_url($value);
}
}


Thanks for all your help!

Answer

Do it like this, instead:

foreach ($resources as $key => $value) {
    foreach ($value as $subKey => $subValue) {
        if (substr($subKey, -5) == '_file') {
            $resources[$key][$subKey] = get_image_id_from_url($subValue);
        }
    }
}

The first issue is that you have an array of arrays, and you were only looping through the outer array. The second issue is that $value can't be modified inside the foreach() loop in this way. We can also use substr($key, -5) == '_file' to make sure '_file' is at the end of the string.

Comments