我有一个像这样的json:
{"response":{"count":7,"list":[{"kdTeacher":"001","nmTeacher":"Eulis Irma"},{"kdTeacher":"002","nmTeacher":"Ni Wayan"},{"kdTeacher":"003","nmTeacher":"Dwi Widi"}]},"metaData":{"message":"OK","code":200}}
我希望教师名称和教师代码显示在下拉列表中。
在我的控制器中这样:
$model=new Teacher;
$paises = file_get_contents(Yii::getPathOfAlias('webroot.assets') .
DIRECTORY_SEPARATOR . "teacher.json");
$jsondecode = CJSON::decode($paises, true);
$temp = array();
foreach ($jsondecode as $key => $value) {
$temp[] = $value;
}
$this->render('techer', array(
'data'=>$temp,
'model'=>$model,
));
}
并在视野中
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->dropDownList($model,'nama',CHtml::listData($data,'kodeTeacher','nmTeacher')); ?>
<?php echo $form->error($model,'name'); ?>
</div>
ID
答案 0 :(得分:0)
问题是您无法获取教师数据,因为您对foreach循环使用了错误的数据。教师代码和名称存储在已解码的json的['response']['list']
索引处。看看:
$model=new Teacher;
$paises = file_get_contents(Yii::getPathOfAlias('webroot.assets') .
DIRECTORY_SEPARATOR . "teacher.json");
$decodedJson = json_decode($paises, true);
$temp = array();
//check if list of teachers is available
if(isset($decodedJson['response']) && isset($decodedJson['response']['list']))
{
//use foreach on ['response']['list'] index - here are teachers data stored
foreach($decodedJson['response']['list'] as $teacher)
$temp[$teacher['kdTeacher']] = $teacher['nmTeacher'];
}
$this->render('techer', array(
'data'=>$temp,
'model'=>$model,
));
从JSON获取教师数据的工作示例:CLICK!!!
在视图中(现在您不需要使用CHtml::listData
方法):
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->dropDownList($model,'nama',$data); ?>
<?php echo $form->error($model,'name'); ?>
</div>