YII2 来自 JSON 链接的下拉列表



如何将 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数据填充到活动表单下拉列表中

最简单的方法是在数组之前为 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 数据的数组格式。

最新更新