2017-05-19 95 views
-1

我不能在yii2中的registerJS的javascript代碼中使用foreach php代碼。瀏覽器顯示「PHP解析錯誤 - yii \ base \ ErrorException語法錯誤,意外'foreach'(T_FOREACH)」錯誤。這裏是我的代碼:如何在yii2的registerJS()javascript代碼中使用foreach php代碼?

<canvas id="bar-chart" width="500" height="150"></canvas> 

<?php 
$lang = Yii::$app->language; 
$title = 'title_'.$lang; 

$this->registerJs(" 
       new Chart(document.getElementById('bar-chart'), { 
       type: 'bar', 
       data: { 
        labels: [ 
           " . foreach ($models as $model) { . " 
            ' " . $model->$title . " ', 
           " . } . " 
          ], 
        datasets: [ 
        { 
         label:'Label', 
         backgroundColor: ['#3e95cd', '#8e5ea2','#3cba9f', '#e7fc00'], 
         data: [479,1654,499, 2632] 
        } 
        ] 
       }, 
       options: { 
        legend: { display: false }, 
        title: { 
        display: true, 
        text: 'Title' 
        } 
       } 
      }); 
    ", yii\web\View::POS_READY); 
+0

什麼版本的PHP您使用的是? –

+0

我正在使用PHP 5.5版本 –

+0

我寫了正確的PHP代碼在JS代碼我的代碼? –

回答

0

我會從JavaScript輸出拉出foreach代碼。

<?php 
$titles = []; 
foreach($models as $model) 
{ 
    $titles[] = sprintf("'%s'", $model->title); 
} 

$titlesText = implode(',', $titles); 

$this->registerJs(" 
       new Chart(document.getElementById('bar-chart'), { 
       type: 'bar', 
       data: { 
        labels: [ 
         ".$titlesText." 
          ], 
        datasets: [ 
        { 
         label:'Label', 
         backgroundColor: ['#3e95cd', '#8e5ea2','#3cba9f', '#e7fc00'], 
         data: [479,1654,499, 2632] 
        } 
        ] 
       }, 
       options: { 
        legend: { display: false }, 
        title: { 
        display: true, 
        text: 'Title' 
        } 
       } 
      }); 
    ", yii\web\View::POS_READY); 
+0

謝謝。有效。 –

0

您不能在字符串中間使用foreach語句。您應該產生從foreach事先來的字符串,然後用JS字符串加入吧:

$mystring = ""; 
foreach ($models as $model) { 
    $mystring .= "' " . $model->$title . " ',"; 
} 

$this->registerJs(" 
       new Chart(document.getElementById('bar-chart'), { 
       type: 'bar', 
       data: { 
        labels: [ $mystring ], 
        datasets: [ 
        { 
         label:'Label', 
         backgroundColor: ['#3e95cd', '#8e5ea2','#3cba9f', '#e7fc00'], 
         data: [479,1654,499, 2632] 
        } 
        ] 
       }, 
       options: { 
        legend: { display: false }, 
        title: { 
        display: true, 
        text: 'Title' 
        } 
       } 
      }); 
    ", yii\web\View::POS_READY); 
+0

非常感謝! –

+0

@AlisherNasrullayev不要忘記標記答案正確,如果它解決了你的問題。 (y)的 –