Search code examples
phparraysmultidimensional-arrayarray-merge

PHP array merge recursive issue


I'm getting an issue when trying to use array_merge_recursive in a foreach. What I'm trying to do is scrape a website then put all of the data into a multidimensional array. Here is my code:

Original Array

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

Array to be merged

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);
}

Output of printing array

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
                    )

            )

    )

)

Why does the first array in the multidimensional array return with

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

There is only meant to be 4 array elements appearing since there is 4 results that will come from the foreach


Solution

  • The empty first result comes from your definition:

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