I have following code. I'm trying to make it simpler and shorter. I created $data1 array and added relevant data with array_merge and saved it to my model. But note that $data1 and $exists has same code inside. Is it possible to pass $data1 array to MyModel's find method without rewriting same code ?
Because of I need to create multiple rows in these snippet, I used MyModel->create. In this code I pasted two blocks, but originally I have 6 blocks like this. So shortening is important for me.
As summary: I need to shorten this code snippet, I don't want to rewrite same data in each block.
$usersNew=array("mike", "john");
$usersLost=array("anna", "maria");
$data1 = array('userid' => $userid,
'date' => date('Y-m-d')
);
foreach ($usersNew as $f) {
$data2 = array_merge($data1, array("users_new" => $f));
$exists=$this->MyModel->find('first',
array('conditions' => array(
'MyModel.userid' => $userid,
'MyModel.date' => date('Y-m-d'),
'MyModel.users_new' => $f
) ));
if ($exists == FALSE) {
$this->MyModel->create();
$this->MyModel->save($data2);
}
}
foreach ($usersLost as $f) {
$data2 = array_merge($data1, array("users_lost" => $f));
$exists=$this->MyModel->find('first',
array('conditions' => array(
'MyModel.userid' => $userid,
'MyModel.date' => date('Y-m-d'),
'MyModel.users_lost' => $f
) ));
if ($exists == FALSE) {
$this->MyModel->create();
$this->MyModel->save($data2);
}
}