J. Doe
J. Doe

Reputation: 73

How to generate a multi-dimensional array from a PDO resultset?

I am trying to make an array using the resultset from a PDO query.

I am not sure how to generete my desired array structure.

require_once("../resource/Database.php");

$query ="SELECT username FROM users";
$select = $db->prepare($query);
$select->execute(array());  
foreach($select as $rs) :          
    $testing = "array('city'=>".$rs['citynames']"),"

$cities = array(
    echo $testing;
);  

I would like this result:

$names= array(
    array('name'=>'Los Angeles'),
    array('name'=>'Chicago'),
    array('name'=>'Houston'),
    array('name'=>'Phoenix'),
    array('name'=>'Philadelphia'),
    array('name'=>'San Antonio'),
    array('name'=>'Dallas',),
    array('name'=>'San Diego',),
    array('name'=>'San Jose', ),
    array('name'=>'Detroit', ),
    array('name'=>'San Francisco',),
    array('name'=>'Jacksonville', ),
    array('name'=>'Indianapolis', ),
    array('name'=>'Austin', ),
    array('name'=>'Columbus', ),
    array('name'=>'Fort Worth',),
    array('name'=>'Charlotte', ),
    array('name'=>'Memphis', ),
    array('name'=>'Baltimore', ),
);

Upvotes: 1

Views: 716

Answers (2)

Rasclatt
Rasclatt

Reputation: 12505

Presumably you are trying to do this?

require_once("../resource/Database.php");
$query ="SELECT username FROM users";
$select = $db->prepare($query);
$select->execute(array());
# You may have a snippet of code that you are missing, but incase not,
# you have to fetch the results while() to iterate or your results. I just
# copied your code and focused on the push, not the fact you didn't fetch
while($rs = $select->fetch(PDO::FETCH_ASSOC)) {
    $names[] = array('name'=>$rs['citynames']);
}

This is an array push found here in the manual. If this is not what you mean, you will have to clarify.

Upvotes: 2

Haithem DISSEM
Haithem DISSEM

Reputation: 74

You should specify the sql query output format :

$query ="SELECT username FROM users";
$select = $db->prepare($query);
$select->execute(array());  
foreach($select->fetchAll(PDO::FETCH_ASSOC) as $rs) {
   $testing[] = array('city' => $rs['citynames']);
}

var_dump($testing);

Upvotes: 2

Related Questions