0

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 ?

1
  • 1
    You can probably get the SQL server to do all this for you without having to resort to juggling all the data in PHP. Look up aggregate functions. Commented Mar 5, 2015 at 17:02

2 Answers 2

1
foreach($rows as $row){
    $data[$row['type']][$row['period']] = $row['val']);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.