pepe
pepe

Reputation: 9909

PHP/Smarty - Need help with multi array and foreach loop

I use this code:

$result = mysql_query("SELECT * FROM data WHERE user_id='$user_id'");

$output_array = array();
while ($row = mysql_fetch_array($result)) {
    if(!isset($output_array[$row['plant_id']]) || !is_array($output_array[$row['plant_id']])){
        $output_array[$row['plant_id']] = array();
    }

    $output_array[$row['plant_id']][$row['date']] = $row['value'];
}

to get this array:

Array
(
    [100] => Array
    (
        [2011, 03, 03] => 111111
        [2010, 12, 03] => 123123
    )

    [101] => Array
    (
        [2011, 01, 01] => 123555
        [2011, 01, 27] => 999
        [2011, 04, 20] => 123555
    )
)

Using Smarty I looped this values as follows (inside JS):

      {foreach from=$output_array key=plant_id item=date_value}
            name: '{$plant_id}',
            data: [{foreach key=date item=value from=$date_value}
                [Date.UTC({$date}), {$value}],
                {/foreach}]
        {/foreach}

But now I would like to get this working back on raw PHP (without Smarty) - does anyone know how to translate these Smarty loops back to PHP?

Any help / pointers are much appreciated!

Upvotes: 1

Views: 601

Answers (1)

alex
alex

Reputation: 490133

I used the alternative control structure syntax (foreach(): ... endforeach instead of foreach() { ... }) because I believe it is clearer in views and it is widely used.

<?php foreach($output_array as $plant_id => $date_value): ?>
   name: '<?php echo $plant_id; ?>',
   date: [<?php foreach($date_value as $date => $value): ?>
          [Date.UTC(<?php echo $date; ?>, <?php echo $value; ?>],
         <?php endforeach; ?>]
<?php endforeach; ?>

BTW, if this is JavaScript, you should know that IE trips up on trailing , in lists.

Also, besides calling Date.UTC, you could echo this data structure as JSON easily by using json_encode().

Upvotes: 2

Related Questions