簡體   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