[英]Does str_replace go through multidimensional arrays?
I have an array setup like so: 我有这样的数组设置:
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] =>
)
)
and I'm trying to use str_replace to remove the "my." 并且我正在尝试使用str_replace删除“我的”。 out of the value4 field of these arrays. 这些数组的value4字段之外。 str_replace("my.", "", $myarray);
but it's not changing anything. 但这并没有改变任何东西。 Does str_replace work on multidimensional arrays? str_replace是否可用于多维数组?
No, it works on strings, or single dimension arrays.... you could use it through the callback in an array_walk_recursive though 不,它适用于字符串或一维数组。...尽管您可以通过array_walk_recursive中的回调使用它
array_walk_recursive(
$myarray,
function (&$value) {
$value = str_replace('.my', '', $value);
}
);
You can use array_walk_recursive()
http://php.net/manual/en/function.array-walk-recursive.php to perform a replacement on every sub-element (Note: Callback is just triggered for leafs (non-arrays)): 您可以使用array_walk_recursive()
http://php.net/manual/en/function.array-walk-recursive.php对每个子元素执行替换(注意:回调仅针对叶子 (非数组)触发) ):
$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 ) )
if the replacement should only appear on value4
keys - add that as a condition: 如果替换项仅出现在value4
键上-将其添加为条件:
function removeMy(&$element, $index){
if ($index === "value4"){
$element = str_replace("my.", "", $element);
}
}
Make it easy 轻松一点
foreach ($array as &$item)
$item['value4'] = str_replace('my.', "", $item['value4']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.