Jump to content

Constructing an array


-Karl-

Recommended Posts

Basically, I've been trying to create an array dynamically from a mysql database.

 

I have a query where I select the id and username from the table, but I want to dynamically build an array from it.

 

Right now my array is:

Array
(
    [0] => Array
        (
            [id] => 1
            [username] => karl
        )

    [1] => Array
        (
            [id] => 2
            [username] => admin
        )

)

 

However, I'm having difficulty trying to get it to look like this:

Array
(
    [id] => Array
        (
            [1] => 1
            [2] => 2
        )

    [username] => Array
        (
            [1] => karl
            [2] => admin
        )

)

 

So that I can just call $row['id'][$i]; to display both id's in a table, or whatever.

 

The only problem is, I need the rows from the mysql database to dynamically construct the array.

 

So say I select id, username, password, the above array will create another part:

    [password] => Array

        (

            [1] => passforkarl

            [2] => passforadmin

        )

 

I'm not sure if that makes an sense at all, but I just can't get my mind around it.

Link to comment
https://forums.phpfreaks.com/topic/263966-constructing-an-array/
Share on other sites

Still no luck, here is what I have at the moment:

public function selectIt($table, $rows = '*', $where = null, $order = null) {
        $q = 'SELECT '.$rows.' FROM `'.$table.'`';
        if($where != null)
            $q .= ' WHERE '.$where;
        if($order != null)
            $q .= ' ORDER BY '.$order;
            
        $query = $this->db->prepare($q);
        $query->execute();                     
        $row = $query->fetchAll(PDO::FETCH_ASSOC);
        $hi = count($row);
        
        $arr = array();
        $query->execute(); 
            while ($row = $query->fetchAll(PDO::FETCH_ASSOC)) {   
                foreach ($row as $k => $v) {
                    $arr[$k][] = $v;
                } 
            }  
            echo '<pre>';
            print_r($arr);
            echo '</pre>'; 

    }

 

Which returns this:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [username] => karl
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [id] => 2
                    [username] => admin
                )

        )

)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.