Assigning array data to a model properties in Yii
I am working on a method to activate new members. I get the following error:
Undefined offset: 1
The error occurs on the line which contains the following:
$model->username=$data[1];
Is there a Yii way to make this work better?
I am a rookie with php, oop, and Yii, so any assistance would be appreciated greatly!
The method basically takes a get request from a user. The get runs this method and contains a key which is used to validate their account. Validations are stored in a file with the same name开发者_运维问答 as the key. Inside the file is a pipe delimited line that contains the date, username, email, salt, and a password hash. After reading the file, and exploding the data at the pipe, I need to assign the data to the model, and then it will be saved to the db.
...
$model=new Users;
$model->activation_key=$_GET['key'];
$path_to_validation_files = Yii::app()->basePath."/data/new_member_validations";
$validation_file = $path_to_validation_files . "/".$model->activation_key.".dat";
if(is_readable($validation_file) && !empty($validation_file))
{
if($fp = fopen($validation_file, 'r'))
{
while(!feof($fp))
{
$line = fread($fp, filesize($validation_file));
}
fclose($fp);
$data = explode('|', $line);
if(!empty($data)){
$model->username=$data[1];
$model->email=$data[2];
$model->salt=$data[3];
$model->password=$data[4];
} else {
throw new CHttpException(500,'Validation file contained no data.');
}
} else {
throw new CHttpException(500,'Cannot open validation file.');
}
} else {
throw new CHttpException(404,'Validation file not found, not readable, or empty.');
}
...
You can use the attributes
property of the CActiveRecord
class to load an associative array.
For example, say you have a model with properties foo
and bar
, and you have an array data('foo'=>1, 'bar'=2)
you can set $myModel->attributes = data
, and it will loop through the array and assign the properties to the model (but only if those attributes have validation rules)
I had a similar problem especially when using an array of array. This is how i solved it.
public function epidemicSelectInsertParticipant($class){
$data= Participant::findAll(['class'=>$class]);
if($data){
foreach ($data as $value) {
$model = new Epidemicparticipant;
foreach ($value as $key => $val) {
if($key=='id'){
}else{
$model->$key = $val;
}
}
$model->save(false);
}
return TRUE;
} else {
return false;
}
}
In my case,$data
is a multi-dimensional array.They keys($key)of $value
are the same as $model->attributes
.
精彩评论