簡體   English   中英

在嵌套關聯數組中查找鍵

[英]Find key in nested associative array

前幾天我問了一個與此相關的問題,我得到了一個答案,但它沒有做我想要的。 這是我遍歷多維關聯數組的方法,檢查一個鍵是否在數組中(從我之前的問題的答案):

private function checkKeyIsInArray($dataItemName, $array)
{
    foreach ($array as $key => $value)
    {
        // convert $key to string to prevent key type convertion
        echo '<pre>The key: '.(string) $key.'</pre>';

        if ((string)$key == $dataItemName)
            return true;

        if (is_array($value))
            return $this->checkKeyIsInArray($dataItemName, $value);

    }
    return false;
}

這是我的數組結構:

Array (
    [0] => Array ( [reset_time] => 2013-12-11 22:24:25 )
    [1] => Array ( [email] => someone@example.com )
)

該方法遍歷第一個數組分支,但不遍歷第二個。 有人可以解釋為什么會出現這種情況嗎? 好像我錯過了什么。

問題是無論遞歸調用是否成功,都會返回遞歸調用返回的內容。 只有在遞歸期間找到密鑰時才應該返回,否則你應該繼續循環。

private function checkKeyIsInArray($dataItemName, $array)
{
    foreach ($array as $key => $value)
        {
            // convert $key to string to prevent key type convertion
            echo '<pre>The key: '.(string) $key.'</pre>';

            if ((string)$key == $dataItemName)
                return true;

            if (is_array($value) && $this->checkKeyIsInArray($dataItemName, $value))
                return true;

        }
    return false;
}

順便說一下,為什么這是一個非靜態函數? 它似乎不需要任何實例屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM