0

我目前PHP Catchable fatal error: Argument 2 passed to NUI::recArrInterKey() must be an array, string given在尝试递归地与多维数组(灰/白名单)相交时收到错误消息。

$foo['contact']['im']['provider']由于某种我无法弄清楚的原因,它似乎在该部分绊倒?

这是我正在使用的示例白名单数组 ($array2)

Array
(
    [location] => false
    [network_name] => false
    [interests] => false
    [last_name] => false
    [url] => false
    [significant_other] => false
    [network_domains] => false
    [contact] => Array
        (
            [im] => Array
                (
                    [provider] => false
                )

            [email_addresses] => false
        )

)

以及方法

/**
 * Recursive array intersect key
 */
private static function recArrInterKey(array $array1, array $array2) 
{
    $array1 = array_intersect_key($array1, $array2);
    foreach ($array1 as $key => &$value) 
    {
        if (is_array($value)) 
        {
            $value = self::recArrInterKey($value, $array2[$key]);
        }
    }
    return $array1;
}

可以说这是$array1

Array
(
    [location] => Seattle
    [occupation] => Developer
    [network_name] => foo.network
    [network_region] => foo.region
    [interests] => coding
    [last_name] => daniel
    [url] => false
    [id] => 4665228
    [significant_other] => some girl
    [network_domains] => false
    [contact] => Array
        (
            [im] => Array
                (
                    [provider] => aol
                )
            [phone] => Array
                (
                    [provider] => at&t
                )

            [email_addresses] => dont@mail.me
        )

)

我期待这是一个回报

Array
(
    [location] => Seattle
    [occupation] => Developer
    [network_name] => foo.network
    [interests] => coding
    [last_name] => daniel
    [url] => false
    [significant_other] => some girl
    [network_domains] => false
    [contact] => Array
        (
            [im] => Array
                (
                    [provider] => aol
                )
            [email_addresses] => dont@mail.me
        )

)
4

2 回答 2

4

因为您正在使用array_intersect_key,它只比较键 =>$array1[$key]可能有一个值作为数组但不是必需的$array2[$key]

你的情况是一个方向相交:recArrInterKey($a1, $a2)不一样recArrInterKey($a2, $a1)

试试这个修复:

private static function recArrInterKey(array $array1, array $array2) 
{
    $array1 = array_intersect_key($array1, $array2);
    foreach ($array1 as $key => &$value) 
    {
        if (is_array($value)) 
        {
            $value = is_array($array2[$key]) ? self::recArrInterKey($value, $array2[$key]) : $value;
        }
    }
    return $array1;
}
于 2013-04-18T21:35:37.423 回答
3

好吧 - 你不检查第二个参数:$array2[$key]- 这也应该是一个数组

于 2013-04-18T21:35:19.203 回答