recently I came across a problem where I would need to generate an object from CodeIgniter PHP foreach loop. Basically I need to filter through my email list and generate the object based on the result, then pass it to the view and use another foreach loop to list the content out there.
Here's what I have and it successfully generates an array $email_raw, but I couldn't find the right way to generate it as an object instead:
PHP:
$email_preliminary=$this->db->select('email')->get('user');
$email_raw = array();
foreach ($email_preliminary->result() as $row):
$email_to_test=$row->email;
if(filter_var($email_to_test, FILTER_VALIDATE_EMAIL)||preg_match('/\d*[1-9]\d*/', $email_to_test))
{
$email_raw[] = $email_to_test;
}
else{
}
endforeach;
People suggested that I use:
$email_raw[] = (object)array('email'=>$email_to_test);
But the error msg says its not an object.
What are other ways I can generate $email_raw as an object so I can pass it to the view and use foreach to list the content out there?
Many thanks!
Update:
per request, here's rest of the controller:
$data['record']=array_unique($email_raw);
$this->load->view('login&signup/signup_test_get_wrong_email_view', $data);
and the view I use:
<?php foreach ($record->result() as $row): ?>
<span><?php echo $row->email; ?></span><br>
<?php endforeach; ?>
foreach can iterate object and arrays. You don't have to convert your array to object.
Leave the controller like it is above:
$email_preliminary=$this->db->select('email')->get('user');
$email_raw = array();
foreach ($email_preliminary->result() as $row):
$email_to_test=$row->email;
if(filter_var($email_to_test, FILTER_VALIDATE_EMAIL)||preg_match('/\d*[1-9]\d*/', $email_to_test))
{
$email_raw[] = $email_to_test;
}
else{
}
endforeach;
// ... code
$data['record']=array_unique($email_raw);
$this->load->view('login&signup/signup_test_get_wrong_email_view', $data);
In the view you simply iterate that array you've just constructed:
<?php foreach ($record as $email): ?>
<span><?php echo $email; ?></span><br>
<?php endforeach; ?>
I guess your doubt comes from lack of knowing how the $data['record']
variable looks like. Use print_r($data['record']);
right after $data['record']
is being set.