开发者

Returning database results as an array

开发者 https://www.devze.com 2023-02-19 08:04 出处:网络
I have the following code: $a=array( \'last\' => array(\'Ford\', \'Smith\', \'Jones\', \'Thomas\'), \'first\' => array(\'Joe\', \'Kyle\', \'Nick\'),

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, 开发者_StackOverflow社区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.

0

精彩评论

暂无评论...
验证码 换一张
取 消