【问题标题】:need help iterating through array generated by yaml (php)需要帮助遍历由 yaml (php) 生成的数组
【发布时间】:2015-01-15 14:53:37
【问题描述】:

我正在创建一个 symfony2 应用程序,用于搜索和替换文件中的字符串

我创建了一个yaml文件,内容如下:

parameters:
         file.search_and_replace:
                 "path/dir/filename":
                        replace: 'word'
                        with: 'anotherword'

                 "path_2/dir/filename_2":
                        replace: 'apples'
                        with: 'oranges'

现在要获取内容,我使用以下语法:

$array = $this->getContainer()->getParameter('file.search_and_replace');

如果我像这样转储变量:

var_dump($array);

返回

array(2) 
{
  'path/file/filename' =>
    array(2) 
    {
      'replace' => string(4) "word"
      'with' => string(11) "anotherword"
    }
  'path_2/file/filename_2' =>
    array(2) 
    {
     'replace' => string(6) "apples"
     'with' =>    string(7) "oranges"
    }
}

我需要找到一种方法来循环遍历这个数组 所以我可以将内容传递给我创建的函数,该函数需要以下参数:

searchAndReplace('filepath','replace_this_word','with_this_word');

类似:

foreach($array as $file)
{
    searchAndReplace($file.path,$file.replace,$file.with);  
}

【问题讨论】:

    标签: php arrays symfony yaml


    【解决方案1】:

    你已经接近了。

    两件事:

    1. foreach 可以接受 key => value 语法。使用这个你可以得到 路径
    2. PHP 不对数组使用点表示法。它用 括号。

    尝试以下方法:

    foreach ($array as $path => $sub) {
        searchAndReplace($path,$sub['replace'],$sub['with']);  
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-21
      • 2011-09-26
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      相关资源
      最近更新 更多