1

I am going to construct a popup javascript in php like this:

$popup_title = array(); 
$popup_text = array(); 
$popup_time = array();
$popup_delay = array(); 

array_push($popup_title, T_gettext("Ready for ..."));
array_push($popup_text, "<a href=\"x.php\">".T_gettext("Click here to...")."</a>"); 
array_push($popup_time, 3000);  
array_push($popup_delay, 6000); 

here I make the javascript code:

if(!empty($popup_title)){
//constuct javascript

$popups = array();
foreach ( $popup_title as $key => $title )
{
    $popups[$key] = new stdClass();
    $popups[$key]->title = $title;
}
foreach ( $popup_text as $key => $text )
{
    $popups[$key]->text = $text;
}
foreach ( $popup_time as $key => $time )
{
    $popups[$key]->time = $time; 
}
//print javascript
echo "
<script type=\"text/javascript\">
$(document).ready(function(){"; 
foreach ( $popups as $popup ):
echo "
    setTimeout(function() {
        $.gritter.add("; echo json_encode($popup); echo ");
    }, ".($popup_delay");"; // <---------Here I need to place popup_delay 
    endforeach;
echo "  
});
</script>"; 

This gives this javascript for example:

<script type="text/javascript">
$(document).ready(function(){
    setTimeout(function() {
        $.gritter.add({"title":"Ready for..","text":"<a href=\"x.php\">Click here to...<\/a>","time":3000});
    }, 0);  
});
</script>

I am not used to foreach. a for loop would be something like this: for($n=0; $n < count($popup_delay); $n++){ echo $popup_delay[$n]; } , but how do I loop through the $popup_delay values with foreach, when I already use json_encode($popup) from foreach ( $popups as $popup ):

2
  • JSON Decode it back to a PHP array? php.net/manual/en/function.json-decode.php Commented Jan 18, 2011 at 13:24
  • You can nest foreach statements Commented Jan 18, 2011 at 13:24

1 Answer 1

1

You just need to use a single key for your array. So instead of creating multiple arrays in PHP, you can create a single multidimensional one like so:

$javascript_array = array();
$javascript_array[0]['title'] = "Ready for ...";
$javascript_array[0]['text'] = "Click here to...";
$javascript_array[0]['time'] = 3000;
$javascript_array[0]['delay'] = 6000;

Your array would be shown as such:

if ( !empty ( $javascript_array ) ) {
// dump in your <script> piece here
    foreach ( $javascript_array as $js_entry ) {
// put in your filler pieces here
        echo "Title: ".$js_entry['title'];
        echo "Text: ".$js_entry['text'];
        echo "Time: ".$js_entry['time'];
        echo "Delay: ".$js_entry['delay']; 
   } // end foreach
// closed </script> 
}
Sign up to request clarification or add additional context in comments.

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.