PHP数组合并递归问题

时间:2016-07-25 02:53:30

标签: php arrays multidimensional-array array-merge

尝试在foreach中使用array_merge_recursive时遇到问题。 我正在尝试做的是刮一个网站,然后将所有数据放入一个多维数组。这是我的代码:

原始数组

$apiarray = array(
"response" => array(
    "badges" => array(
        array()
    )
)
);

要合并的数组

foreach($recentbadges as $badge)
{
++$bcount;
$pbadge = $badge->find('div.profile_badges_badge', 0);
$pbadge = strip_tags($badge, '<div><br />');
preg_match('@data-community-tooltip="([^"]+)"@', $pbadge, $matchg);
$pbadge = array_pop($matchg);
$pbadge = array(
    "response" => array(
        "badges" => array(
            array(
                "badge_title" => "{$pbadge}"
            )
        )
    )
);
$apiarray = array_merge_recursive($arrayfull, $pbadge);
}

打印数组输出

Array
(
[response] => Array
    (
        [badges] => Array
            (
                [0] => Array //Why does this data appear?
                    (
                    ) 

                [1] => Array
                    (
                        [badge_title] => Heraldbr Level 2 Skullgirls Badge
                    )

                [2] => Array
                    (
                        [badge_title] => Gold Cubebr Level 5 GooCubelets Badge
                    )

                [3] => Array
                    (
                        [badge_title] => Four Color Acesbr Level 5 Why So Evil 2: Dystopia Badge
                    )

                [4] => Array
                    (
                        [badge_title] => Teleport Controllerbr Level 3 Heaven Island Life Badge
                    )

            )

    )

)

为什么多维数组中的第一个数组以

返回
 [0] => Array //Why does this data appear?
                    (
                    ) 

只有4个数组元素出现,因为有4个结果将来自foreach

2 个答案:

答案 0 :(得分:2)

空的第一个结果来自您的定义:

$apiarray = array(
    "response" => array(
        "badges" => array(
            array() // <- remove this guy
        )
    )
);

答案 1 :(得分:1)

从原始数组中的徽章中删除array(),例如:

$apiarray = array(
    "response" => array(
        "badges" => array()
    )
);