简体   繁体   中英

foreach loop in php to construct javascript

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]; } 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 ):

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> 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM