1

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!

1 Answer 1

2

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().

Sign up to request clarification or add additional context in comments.

2 Comments

thanks so much!! in fact i'm trying to port this to CodeIgniter, but as I see i'll need to change a few things. any suggestions?
@imcl Build an array, and then join($array, ',')

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.