Manipulating query results

#1
[eluser]kjackson7_93[/eluser]
I have an application that queries a table. A field in the table is the name of a file that should be in the file system. I'd like to loop through the results, test to make sure the file exists. Currently (not CI nor MVC) I do:

Code:
$notes_sth = $dbh->prepare($sql);
$notes_sth->execute(array($_SESSION['userid']));
while ($rec = $notes_sth->fetch()){
    $rec['has_external_doc'] = file_exists(DOCUMENTROOT."/notes/".$rec['board_notes_id'].$rec['filename_ext']) ? 1 : 0;
    $notes_array[] = $rec;
}

Using CI, in my model I do:
Code:
$board_notes = $this->db->get('board_notes');
return $board_notes->result();

How can I loop through $board_notes->results, insert "has_external_doc" and still return the same data structure as $board_notes->result()?

Thanks in advance.

#2
[eluser]Clooner[/eluser]
Use $board_notes->result_array() and then loop through the array using for or foreach. This all has very good documentation. See Generating Query Results

Update and to convert an array back to object...
You could use something like this
Code:
function array2obj($data)
{
  return is_array($data) ? (object) array_map(__FUNCTION__,$data) : $data;
}
This would be handy in the array helper...

#3
[eluser]kjackson7_93[/eluser]
[quote author="clooner" date="1204802787"]Use $board_notes->result_array() and then loop through the array using for or foreach. This all has very good documentation. See Generating Query Results

Update and to convert an array back to object...
You could use something like this
Code:
function array2obj($data)
{
  return is_array($data) ? (object) array_map(__FUNCTION__,$data) : $data;
}
This would be handy in the array helper...[/quote]

Thanks! I like the array2obj function. I'll look into adding it.

I ended up putting the loop and testing for the existence of the file in the view. I was debating if that is the proper place for it. I know using MVC isn't about separating HTML from PHP but rather separating display logic from controller logic. So in that way I could rationalize that adding logic to display a link only if a file exists is ok... BUT having too much (whatever that means) PHP code in a view page makes it more complicated for a designer with little or no programming experience to work in the views. It's all about trade offs and I usually try to err on the side of less PHP in views.

I will put array2obj into an array helper and give it a try. Thanks again.


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


Users browsing this thread:
1 Guest(s)


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.