递归 PHP 到数组的最佳方式

Best way recursive PHP to array

我必须获取多维数组的元素并且我有这个解决方案,但我认为这是一个粗鲁的解决方案... 有没有更好的方法来解决这个问题?

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
)

您可以使用array_walk_recursive函数

function extractElement($array, $element) {

    $match = [];

    array_walk_recursive( $array, 
          function ($v) use (&$match, $element) { 
               if ($v == $element)  $match[] = $v; 
               });
    return $match;
}

demo on eval.in