Clement
Clement

Reputation: 51

PHP - Incrementally add array value

Basically I have this from a query:

Array
(
[0] => Array
    (
        [period] => 2014-03
        [val] => 2.19
        [type] => TypeX
    ),
[1] => Array
    (
        [period] => 2014-03
        [val] => 2.02
        [type] => TypeY
    )
)

Using a foreach loop to populate another array we will call DATA, I want the to get the following:

Array
(
[TypeX] => Array
    (
        [2014-03] => 2.19
    )
[TypeY] => Array
    (
        [2014-03] => 2.02
    )
 )

The whole thing is looped because my query needs to run each time for a different period. Current exemple, second loop would run for 2014-04. My problem is when I arrive for the 2nd time at my DATA array, I want this:

Array
(
[TypeX] => Array
    (
        [2014-03] => 2.19
        [2014-04] => 1.10

    )
[TypeY] => Array
    (
        [2014-03] => 2.02
        [2014-04] => 4.74
    )
)

My code is roughly like this:

$data = array();
foreach($graph_period as $period){
$rows = Queryfunction($period,$WHERE,$byType);
        foreach($rows as $row){
            $data[$row['type']] = array($row['period']=>$row['val']);
        }
}

Because the key of the first level (TypeX, TypeY) are the same, the valei is overwritten. How am I to append the array instead of overwriting ?

Upvotes: 0

Views: 95

Answers (2)

kainaw
kainaw

Reputation: 4334

You only need to change a tiny bit. Inside the foreach where you set the value:

if( !isset($date[$row['type']]) ) {
  $data[$row['type']] = array();
}

$data[$row['type']][$row['period']] = $row['val'];

So, you create the array only if it does not exist.

Upvotes: 0

zim32
zim32

Reputation: 2619

foreach($rows as $row){
    $data[$row['type']][$row['period']] = $row['val']);
}

Upvotes: 1

Related Questions