Kannan Lg
Kannan Lg

Reputation: 921

Convert a php resultset into an array

I am trying to convert a php resultset into an array (using foreach), I'm not quite doing it right..

I have a resultset:

$result

I am looping through it as below: (horribly wrong)

while($row = mysql_fetch_array($result)) {

    foreach (mysql_fetch_array($result) as $k => $v) {
      echo "Fred's $k is ". $v['uid']. "\n";
    }

}

I want this array to be in the below format:

Array
(
    [0] => Array    //row1
        (
            [column1] => value
            [column2] => value
            [column3] => value
        .
        .

        )

    [1] => Array    //row2
        (
            [column1] => value
            [column2] => value
            [column3] => value
        .
        .
        )

    [2] => Array    //row3
        (
            [column1] => value
            [column2] => value
            [column3] => value
        .
        .
        )

)

I am a newbie, please help.

Upvotes: 1

Views: 27567

Answers (6)

mickmackusa
mickmackusa

Reputation: 47863

As demonstrated here, you do not need to call a fetching function to access the result set values.

$resultArray = [];
foreach ($resultSetObject as $row) {
    $resultArray[] = $row;
}

Assuming you have rows in your result set, this will generate an indexed array of associative arrays.

If you want to be selective about which columns are included in your output array, then you can access them by using associative array syntax to refer to the db table's column names ($row['column_a']).

If you want EVERYTHING to go into your array, then you can using mysqli's fetch_all() to skip the manual loop.

Upvotes: 0

Ayman Safadi
Ayman Safadi

Reputation: 11552

Try mysql_fetch_assoc instead:

$results_array = array();
while($row = mysql_fetch_assoc($result)) {
    $results_array[] = $row;
}

Upvotes: 0

Lucas
Lucas

Reputation: 10646

You don't need a foreach to do this, you can just stick with your while loop:

$result_set = array();

while($row = mysql_fetch_array($result)) {
    $result_set[] = $row;
}

Then you can use it like a normal array:

$result_set[0]['column_name'];

Upvotes: 2

KV Prajapati
KV Prajapati

Reputation: 94625

Try this,

while($row = mysql_fetch_assoc($result)) {
   $ar[]=$row;
}

Upvotes: 0

Shoogle
Shoogle

Reputation: 206

    $results = array();
    while($row = mysql_fetch_assoc($result))
    {
        $results[] = $row;
    }

    //$results has all that you need
    print_r($results);

Upvotes: 6

jogesh_pi
jogesh_pi

Reputation: 9782

i can't understand well but hope this will help you :

$array = array();
while($row = mysql_fetch_array($result)) {
 $array[] = $row['uid'];
}

Upvotes: 0

Related Questions