Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当键包含特定字符串时,如何使用php foreach循环更新关联数组中的值?_Php_Arrays_Foreach - Fatal编程技术网

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

当键包含特定字符串时,如何使用php foreach循环更新关联数组中的值?,php,arrays,foreach,Php,Arrays,Foreach,我需要使用php更改关联数组中匹配键的所有值,但我只能通过匹配键中的特定字符串而不是可能更改的整个键名来定位键 在下面的例子中,我需要一种方法来定位所有的“\u文件”键,并将它们的文件名更改为相关的附件ID,但无法定位整个键“bg\u infographic\u file”,因为该键可能会更改为“bg\u whitepaper\u file”或其他名称 当前$resources数组: Array ( [0] => Array ( [bg_in

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

在下面的例子中,我需要一种方法来定位所有的“\u文件”键,并将它们的文件名更改为相关的附件ID,但无法定位整个键“bg\u infographic\u file”,因为该键可能会更改为“bg\u whitepaper\u 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)=''u file'
来确保
''u file'
位于字符串的末尾。

您不做任何更改数组-那么,嗯,您希望发生什么?为什么不将
if(strpos($key,''u file')!==FALSE)
更改为
if(strpos($key,''u file')
打印($resources)在您推荐的foreach循环后仍返回原始数组。由于某种原因,这破坏了页面。太棒了,没问题,很高兴提供帮助!
$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);
        }
    }
}