CodeIgniter Forums
Send qry results to array- retrieve w/specific format for use in JS file - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: Send qry results to array- retrieve w/specific format for use in JS file (/showthread.php?tid=48899)



Send qry results to array- retrieve w/specific format for use in JS file - El Forum - 02-01-2012

[eluser]justmelat[/eluser]
Hi

We want to try a few things using the required fields we have in our CI 1.7.2 app. We've got the query pulling the data we want, but need to dump the data into an array, in a strict format, so we easily work with it in an external JS file. Here is the qry we're using:

$myquery2 = $this->db->query("select account_id, display_name, id from field
where account_id = $holdAcctID and required_flag = 1");

Code:
<?php $toHoldArr = array();
if ($myquery2->num_rows() > 0){
foreach ($myquery2->result() as $row)
        {
            echo $row->account_id;
            echo $row->display_name;
            echo $row->field_id;
            $toHoldArr[] = $row;
        }
}
echo '[removed]';
echo 'var toHoldArr = new Array();';
foreach($myquery2 as $key=>$value)
{
echo 'toHoldArr['.$key.']="'.$value.'";';
}
echo '[removed]';?>
Here's how array is displayed from view source:
Quote:["conn_id"]=>
resource(50) of type (mysql link)
["result_id"]=>
resource(141) of type (mysql result)
["result_array"]=>
array(0) {
}
["result_object"]=>
array(5) {
[0]=>
object(stdClass)#54 (3) {
["account_id"]=>
string(1) "3"
["display_name"]=>
string(20) "Project Requested By"
["id"]=>
string(2) "15"
}
[1]=>
object(stdClass)#52 (3) {
["account_id"]=>
string(1) "3"
["display_name"]=>
string(18) "Project Name/Title"
["id"]=>
string(2) "18"
}
We want it to go into the array var like this:
array[0]
["account_id"] => "3"
["display_name"] => "Project Name/Title"
["id"]=>"18"
array[1]
["account_id"] => "3"
["display_name"] => "Email Us"
["id"]=>"24"
array[2]
["account_id"] => "3"
["display_name"] => "Approver"
["id"]=>"54"
and so on...

Can anyone help?




Send qry results to array- retrieve w/specific format for use in JS file - El Forum - 02-03-2012

[eluser]JRY[/eluser]

Pleaes try this

<?php

foreach ($myquery2->result() as key=>$row)
{

}


?>



Send qry results to array- retrieve w/specific format for use in JS file - El Forum - 02-03-2012

[eluser]CroNiX[/eluser]
If you want an array returned, TELL IT!

Code:
//get the result as an array
$result_array = $myquery2->result_array();

//see what it looks like
echo '<pre>';
print_r($result_array); //should output like you wanted it above...
echo '</pre>';

//make our json from the array
$json_array = json_encode($result_array);

Also, if you are going to be using the result in javascript, it might be better to just json_encode() it.