2011-01-15 59 views
0

我已經建立了我的站點來使用gitter彈出系統。 javascript看起來像這樣:從php中構建javascript陣列

$(document).ready(function(){ 
    setTimeout(function() { 
     $.gritter.add({ 
      title: 'Welcome!', 
      text: 'This appears to be your first time playing. Blablabla', 
      time: '25000' 
     }); 
    }, 500);       
    setTimeout(function() { 
     $.gritter.add({ 
      title: 'Walkthrough', 
      text: 'A walkthrough was setup ...', 
      time: '' 
     }); 
    }, 30000);   
    setTimeout(function() {       
     $.gritter.add({ 
      title: 'You got mail', 
      text: 'You have received a message from x ', 
      time: '' 
     }); 
    }, 36000); 

這是3個彈出窗口的示例。我想要做的是有這樣的數組:

$popup_title[0] = "Welcome!"; 
    $popup_text[0] = "This appears to be ..."); 
    $popup_time[0] = 25000; 

     $popup_title[1] = "Walkthrough"; 
     $popup_text[1] = "A basic blabla ..."); 
     $popup_time[1] = ""; 

並循環這個數組(如果它們不是空的)並基於數組構造javascript。

回答

2

這樣的事情應該做的工作

<?php 
$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; 
} 
?> 
<script type="text/javascript"> 
$(document).ready(function(){ 
    <?php foreach ($popups as $popup): ?> 
    setTimeout(function() { 
     $.gritter.add(<?php echo json_encode($popup);?>); 
    } 
    <?php endforeach; ?> 
} 
</script> 
1

只是回顯了PHP創建的JavaScript代碼。

0

使用多個陣列是有點麻煩,請嘗試使用嵌套的數組,並確保正確逃生的JavaScript的輸出(我沒有這樣做,下面爲了清楚起見)。

$popups = array(
    array('title' => 'First Title', 'text' => 'First Text', 'time' => 25000), 
    array('title' => 'Second Title', 'text' => 'Second Text', 'time' => 2000), 
); 
echo "<script>"; 
foreach($popups as $idx=>$popup) { 
    echo "setTimeout(function() { $.gritter.add({" 
     ."title: '{$popup['title']}'," 
     ."text: '{$popup['text']}'," 
     ."time: ''" 
    ."}); }, {$popup['time']}";  
} 
echo "</script>";