使用RecursiveIteratorIterator php在多维数组中搜索和替换

时间:2015-08-26 11:54:40

标签: php arrays multidimensional-array

我是php和课程的新手,

我有一个多维数组,我想循环并替换字符串的一部分(如果存在)。

这是我的阵列:

$unser = array(
    "a" => "https://technet.microsoft.com",
    "b" => "https://google.com",
    "c" => "https://microsoft.com",
    "d" => array(
              "a" => "https://microsoft.com",
              "b" => "https://bing.com",
              "c" => "https://office.com",
              "d" => "https://msn.com"
          );
);

我要搜索的值是: microsoft ,我想用 stackoverflow 替换它,并保存数组,以便我可以将其与其他功能一起使用例如json_encode。

我能够在数组上循环并搜索该项并替换它但是它没有保存数组我不知道为什么。

<?php

$unser = array(
    "a" => "https://technet.microsoft.com",
    "b" => "https://google.com",
    "c" => "https://microsoft.com",
    "d" => array(
              "a" => "https://microsoft.com",
              "b" => "https://bing.com",
              "c" => "https://office.com",
              "d" => "https://msn.com"
          );
);

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($unser));
foreach($iterator as $key => $value) {
    if (strpos($value,'microsoft') !== false) {
        #echo($value);
        $value = substr_replace('microsoft', 'stackoverflow', $value);
        #echo($value);
    }
}

var_dump(iterator_to_array($iterator,true)); 

?>

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

更新:我看到你更新了你的问题所以现在我的回答并不那么相对。

你可以更容易地做到这一点。你走了:

<?php

$data = array(
    "a" => "https://technet.microsoft.com",
    "b" => "https://google.com",
    "c" => "https://microsoft.com",
    "d" => "https://yahoo.com"
);

foreach ($data as $key => $value) {
    if (strpos($value, 'microsoft') !== false) {
        $data[$key] = str_replace('microsoft', 'stackoverflow', $value);

    }
}

var_dump($data);

结果:

array(4) {
  ["a"]=>
  string(33) "https://technet.stackoverflow.com"
  ["b"]=>
  string(18) "https://google.com"
  ["c"]=>
  string(25) "https://stackoverflow.com"
  ["d"]=>
  string(17) "https://yahoo.com"
}

答案 1 :(得分:0)

你试图以过于复杂的方式去做。您只需使用str_replace()函数(see documentation here for details)即可完成此操作。

对于多维数组:

$data = array(); //Multi-D Array

foreach($data as $key => $subarray)
{
    foreach($subarray as $subkey => $subsubarray)
    {
        if (strpos($value, 'microsoft') !== false)
        {            
            $data[$key][$subkey] = str_replace('microsoft', 'stackoverflow', $value);
        }
    }
}

对于一维数组:

$data = array(
    "a" => "https://technet.microsoft.com",
    "b" => "https://google.com",
    "c" => "https://microsoft.com",
    "d" => "https://yahoo.com"
    );

foreach ($data as $key => $value)
{
    if (strpos($value, 'microsoft') !== false)
    {
        $data[$key] = str_replace('microsoft', 'stackoverflow', $value);
    }
}