feudal
feudal

Reputation: 3

PHP multidimensional associative array with a loop

I'm trying to build a multidimensional associative array but the first array is empty. As you can see the [domain1] array is not showing any associative array items whereas [domain2] is showing the results that should be in the [domain1] array.

foreach ($db->query($sql) as $row) {
            $arr1['domain'.$x] = $arr2;
            $arr2['sum'] = $row['domain' . $x];
            $arr2['core'] = ${"d$x"};
        }

My results look like this.

Array
(
[domain1] => Array
    (
    )

[domain2] => Array
    (
        [sum] => 8
        [core] => 4
    )

[domain3] => Array
    (
        [sum] => 8
        [core] => 3
    )

[domain4] => Array
    (
        [sum] => 8
        [core] => 2
    )

[domain5] => Array
    (
        [sum] => 8
        [core] => 3
    )

[domain6] => Array
    (
        [sum] => 8
        [core] => 6
    )
)

Upvotes: 0

Views: 47

Answers (1)

JesusTheHun
JesusTheHun

Reputation: 1237

You set the array $arr1 in the wrong order. Correct order is :

foreach ($db->query($sql) as $row) {
    $arr2 = array();
    $arr2['sum'] = $row['domain' . $x];
    $arr2['core'] = ${"d$x"};
    $arr1['domain'.$x] = $arr2;
}

Upvotes: 2

Related Questions