繁体   English   中英

当键包含特定字符串时,如何使用php foreach循环更新关联数组中的值?

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

我需要使用php更改关联数组中匹配键的所有值,但我只能通过匹配键中的特定字符串而不是整个键名来匹配它,因为它可能会更改。

在以下情况下,我需要一种方法来定位所有“ _file”键并将其文件名更改为相关的附件ID,但无法定位整个键“ bg_infographic_file”,因为该键可能会更改为“ bg_whitepaper_file”或某些其他名字。

当前的$ resources数组:

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
        )

)

结果是我需要什么:

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
        )

)

我正在考虑遵循这些原则,但由于以下内容仅返回未更改的数组数据,因此我无法弄清楚:

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

感谢你的帮助!

这样做是这样的:

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

第一个问题是您有一个数组数组,而您仅在外部数组中循环。 第二个问题是$value不能以这种方式在foreach()循环内进行修改。 我们还可以使用substr($key, -5) == '_file'来确保'_file'在字符串的末尾。

$findMe = "_file";
foreach ($resources as $key => $value) {
    foreach ($value as $findInMe => $fileName) {
        $pos = strpos($findInMe, $findMe);
        if ($pos !== false) {
            $resources[$key][$findInMe] = get_image_id_from_url($fileName);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM