我有一个像这样的阵列设置:
Array
(
[0] => Array
(
[value1] => John Doe
[value2] => Father
[value3] =>
[value4] => http://www.website.my.com
[value5] =>
[value6] =>
)
[1] => Array
(
[value1] => Jane Doe
[value2] => Mother
[value3] =>
[value4] => http://www.website.my.com
[value5] =>
[value6] =>
)
[2] => Array
(
[value1] => Sara Smith
[value2] => Daughter
[value3] =>
[value4] => http://www.website.my.com
[value5] =>
[value6] =>
)
)
我正在尝试使用str_replace删除“我的”。超出这些数组的value4字段。 str_replace("my.", "", $myarray);
但它并没有改变任何事情。 str_replace是否适用于多维数组?
答案 0 :(得分:4)
不,它适用于字符串或单维数组....你可以通过array_walk_recursive中的回调来使用它但是
array_walk_recursive(
$myarray,
function (&$value) {
$value = str_replace('.my', '', $value);
}
);
答案 1 :(得分:3)
您可以使用array_walk_recursive()
http://php.net/manual/en/function.array-walk-recursive.php对每个子元素执行替换(注意:仅为 leafs (非数组)触发回调):
$myArray = array(0 => "my.test", 2=> array("test" => "my.thing"));
array_walk_recursive($myArray, "removeMy");
function removeMy(&$element, $index){
$element = str_replace("my.", "", $element);
}
print_r($myArray); // Array ( [0] => test [2] => Array ( [test] => thing ) )
如果替换应仅出现在value4
键上 - 请将其添加为条件:
function removeMy(&$element, $index){
if ($index === "value4"){
$element = str_replace("my.", "", $element);
}
}
答案 2 :(得分:2)
轻松实现
foreach ($array as &$item)
$item['value4'] = str_replace('my.', "", $item['value4']);