Hel*_*You 6 php arrays foreach
我需要从 PHP 数组中获取每个键值对。结构不同且不可规划,例如一个键可能包含一个额外的数组等等(多维数组?)。我想调用的函数具有从值中替换特定字符串的任务。问题是函数foreach, each, ... 只使用主键和值。
是否存在foreach具有每个键/值的-function 的函数?
完成此类任务的常用方法是使用递归函数。
让我们一步一步来:
首先你需要foreach控制语句......
http://php.net/manual/en/control-structs.foreach.php
...这让您可以在不事先知道键名称的情况下解析关联数组。
然后is_arrayand is_string(最终is_object,is_integer...)让您检查每个值的类型,以便您可以正确操作。
http://php.net/manual/en/function.is-array.php
http://php.net/manual/en/function.is-string.php
如果找到要操作的字符串则执行替换任务
如果找到一个数组,该函数会调用自己传递刚刚解析的数组。
这样原始数组将被解析到最深层次,而不会丢失和键值对。
例子:
function findAndReplaceStringInArray( $theArray )
{
foreach ( $theArray as $key => $value)
{
if( is_string( $theArray[ $key ] )
{
// the value is a string
// do your job...
// Example:
// Replace 'John' with 'Mike' if the `key` is 'name'
if( $key == 'name' && $theArray[ $key ] == "John" )
{
$theArray[ $key ] = "Mike";
}
}
else if( is_array( $theArray[ $key ] )
{
// treat the value as a nested array
$nestedArray = $theArray[ $key ];
findAndReplaceStringInArray( $nestedArray );
}
}
}
Run Code Online (Sandbox Code Playgroud)