递归PHP到数组的最佳方法
我必须得到多维数组的元素,我有这个解决方案,但我认为这是一个粗糙的解决方案。。。 有没有更好的办法解决这个问题递归PHP到数组的最佳方法,php,coding-style,Php,Coding Style,我必须得到多维数组的元素,我有这个解决方案,但我认为这是一个粗糙的解决方案。。。 有没有更好的办法解决这个问题 function extractElement($array, $element) { $match = []; foreach ($array as $key => $value) { if (is_array($value)) { if ($innerMatch = extractElement($value, $e
function extractElement($array, $element) {
$match = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
if ($innerMatch = extractElement($value, $element)) {
foreach ($innerMatch as $innerKey => $innerValue) {
array_push($match, $innerValue);
}
}
} else {
if ($value === $element) {
array_push($match, $value);
}
}
}
return $match;
}
$array = [1, 4, [4], [1, 2, 3, 4, [1, 2, 4, 4]]];
extractElement($array, 4);
产出:
Array
(
[0] => 4
[1] => 4
[2] => 4
[3] => 4
[4] => 4
)
您可以使用数组\步\递归函数
function extractElement($array, $element) {
$match = [];
array_walk_recursive( $array,
function ($v) use (&$match, $element) {
if ($v == $element) $match[] = $v;
});
return $match;
}