Abs
Abs

Reputation: 57966

Loop through database rows and create a single array

I have nooby PHP question that I can't figure out!

I loop through rows from my database:

    $data = array();

    while($row = sqlsrv_fetch_array($queryResult, SQLSRV_FETCH_ASSOC)){

        $data[] = $row;
    }

$data now contains an array within an array how can I have it so that its still just a single array?

Thanks all

Upvotes: 3

Views: 7225

Answers (4)

Brendan Bullen
Brendan Bullen

Reputation: 11819

This should get you all values returned from all columns and rows as a single dimension array

$data = array();

while($row = sqlsrv_fetch_array($queryResult, SQLSRV_FETCH_ASSOC)){
    $values = array_values($row);
    foreach($values as $value)
    {
        $data[] = $value;
    }
}

Upvotes: 2

brin
brin

Reputation: 1

I see this is an old question, but I was also looking for a solution to this. Came up with the following which works for me:

function mssql_query($conn, $query, array $bind = array()) {
    $stmt = sqlsrv_query($conn, $query, $bind);
    if( $stmt=== false ) {
        // do something with the error information
        // die(print_r(sqlsrv_errors(), true));
        return array();
    }
    sqlsrv_execute($stmt);
    $data = array();
    while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
        array_push($data, $row);
    }
    return $data;
}

Which can be used directly in a foreach loop:

foreach(mssql_query($conn, $query) as $row) {
    echo $row['column'];
}

Or assigned to a variable for counting etc.

$conn is of course the connection (from PHP.net):

$serverName = "server.example.com"; // remember to append instance if applicable
$connectionInfo = array( "Database"=>"dbname", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
    die( print_r( sqlsrv_errors(), true));
}

Upvotes: 0

Alex M
Alex M

Reputation: 3513

It a more obvious way:

$data = array();

while($row = sqlsrv_fetch_array($queryResult, SQLSRV_FETCH_NUMERIC){
  $data = array_merge( $data, array_values($row) );
}

Upvotes: 3

takteek
takteek

Reputation: 7110

That's because each $row is an associative array. If you just want data to be an array of values from one column, specify that column:

$data = array();
while($row = sqlsrv_fetch_array($queryResult, SQLSRV_FETCH_ASSOC)){
    $data[] = $row['column_name_you_want'];
}

Upvotes: 4

Related Questions