简体   繁体   中英

Returning database results as an array

I have the following code:

$a=array(
    'last' => array('Ford', 'Smith', 'Jones', 'Thomas'),
    'first' => array('Joe', 'Kyle', 'Nick'),
    );

I have all these names in my database, and a couple more like age, etc.

How can I pull all the records from the database and set them as a array for $a? I need them to be in the format above

Did you try this:

$query = "SELECT last, first from names"; //whatever the query is...
$results = mysql_query($query);
$all = array();
while($row = mysql_fetch_array($results)){
   foreach($row as $key=>$value){
       if(!isset($all[$key])) $all[$key] = array();
       $all[$key][] = $value;
   }
}

The results would look something like:

$all=array(
    'last' => array('Ford', 'Smith', 'Jones', 'Thomas'),
    'first' => array('Joe', 'Kyle', 'Nick','Allen'),
...
    );

Just to post the obvious...the codeigniter active record application of @Neal's answer would look like this:

$this->db->select('first,last,age');
    $query = $this->db->get('my_table');
    $results = $query->results();
    if($query->num_rows() > 0 ){
        foreach($results as $result as $key=>$value){
            $all[$key][] = $value;
        }

I omitted the check because I typically do that in the view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM