簡體   English   中英

JSON鏈接的YII2下拉列表

[英]YII2 Dropdownlist from JSON link

如何將JSON數據填充到下拉列表

這是json鏈接: http:// localhost / data

這是json格式:

[{"inst_id":"1","inst_code":"001","inst_name":"HARVARD"},{"inst_id":"2","inst_code":"002","inst_name":"UCLA"}]

這個觀點:

<?= $form->field($model, 'institusi')->dropDownList(); ?>

“ inst_id”中的下拉值和“ inst_name”中的文本

我有代碼,但不是活動表格

$url = 'http://localhost/data';
        $content = file_get_contents($url);
        $json = json_decode($content, true);
        $inst=array();
        echo "<select>";
        foreach($json as $item) {

            echo "<option value='".$item['inst_id']."'>".$item['inst_name']."</option>";

        }
        echo "</select>";

那么如何將json數據填充到Activeform Dropdownlist中

最簡單的方法是在其之前為dropDownList准備數組

<?php
        $url = 'http://localhost/data';
        $content = file_get_contents($url);
        $json = json_decode($content, true);
        $instArray = ArrayHelper::map($json,'inst_id','inst_name');
        echo $form->field($model, 'institusi')->dropDownList($instArray);
?>

您還可以從控制器准備相同的數組,並將其傳遞給render方法的視圖。

其他選項是創建組件或向模型添加靜態方法。 兩者都應返回json數據的數組格式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM