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



我是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)); 
?>

提前感谢您的帮助

你试图用一种太复杂的方式来做这件事。您可以简单地使用str_replace()函数(详细信息请参阅此处的文档)来完成此操作。

For Multi Dimensional Array:

$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);
        }
    }
}

For一维数组:

$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);
    }
}

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

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

<?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"
}

相关内容

  • 没有找到相关文章

最新更新