猿问

递归PHP函数查找多维数组中数组中第一次出现的键

我正在尝试递归循环遍历我的多维数组,如果它们的数组有键,我想返回当前数组。


我试图让它尽可能简单,但这返回奇怪的类型错误让我感到困惑。


在 foreach 循环内,如果嵌套项是一个数组,则再次运行该函数,直到找到键的出现。


挠我的头,谁能看出我的问题。谢谢。


<?php

/**

 * @param int|string $key

 * @param array $array

 * @return bool|array

 */

public static function multi_array_key_exists($key,$array): bool

{

    // if array key exist in this dimension

    if (array_key_exists($key,$array)) {

        // return the array

        return $array;

    } else {

        // foreach array as nested item

        foreach ($array as $nested) {

            // if the nested item is an array

            if (is_array($nested))

                // run this function again

                self::multi_array_key_exists($key,$nested);

        }

    }

    return false;

}


哆啦的时光机
浏览 129回答 2
2回答

慕妹3242003

当您进行递归调用时,您会忽略它返回的内容。您应该检查它,看看该调用是否找到了匹配项。代替:self::multi_array_key_exists($key,$nested);和:$res&nbsp;=&nbsp;self::multi_array_key_exists($key,$nested);if&nbsp;($res&nbsp;!==&nbsp;false)&nbsp;return&nbsp;$res;(不要忘记将语句括在大括号中)。只有当所有递归调用都返回时false你才能安全地return false结束函数体。一旦这样的递归调用返回一个匹配项,就没有必要在该foreach循环中保持迭代。您可以立即退出,将相同的信息返回给父执行上下文。另一个问题是,您声明函数返回 a&nbsp;bool,但您希望它有时返回false,有时返回数组(当有匹配项时)。所以那是行不通的。

Helenr

我纠正了你的方法。现在它如你所愿。您还需要删除返回的 bool 类型,因为它可以是数组或布尔值。public static function multi_array_key_exists($key,$array){&nbsp; &nbsp; // if array key exist in this dimension&nbsp; &nbsp; if (array_key_exists($key,$array)) {&nbsp; &nbsp; &nbsp; &nbsp; // return the array&nbsp; &nbsp; &nbsp; &nbsp; return $array;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; // foreach array as nested item&nbsp; &nbsp; &nbsp; &nbsp; foreach ($array as $nested) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // if the nested item is an array&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (is_array($nested)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // run this function again&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $value = self::multi_array_key_exists($key,$nested);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ($value) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return $value;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return false;}
随时随地看视频慕课网APP
我要回答