tags:

views:

52

answers:

3

Hello all,

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

+2  A: 

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'];
}
takteek
Awesome, thanks. Its going to be tedious to type all column names but I get the idea behind your method.
Abs
Hmmm... What's the point of that? In order to properly get all data, you'll need a 2D array anyways. You'll just be switching the order of the dimensions, but there is no way around having a multidimensional array.
quantumSoup
(1) It's an associative array so you'll need to type every column name at least once somewhere to even access the data. (2) Depending on what you need to do with the data, rearranging it may be a waste of time. If you put the rows into `$data` you can always do something like this `$data[0]['column_name'] to access `column_name` in the first row, etc.
takteek
Actually, should it not be `$data['column_name_you_want'] = $row['column_name_you_want'];` so that it stays as a single associative array, rather than an array that holds an associative array?
Abs
@Abs the point is you have rows and columns (hence a table): how would you condense both in a simple plain list?
kemp
If you did that, @Abs, then you would only ever have the data from the last row in your query.
Matt Ellen
+2  A: 

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;
    }
}
Brendan Bullen
+2  A: 

It a more obvious way:

$data = array();

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