1

Likely a remedial question, but in all my days as a PHP user I have yet to encounter an answer. Basically, is there any way to grab a single field of a "mysql_query" as an array? For instance say I have the following:

$query = "Select id,first_name,last_name FROM people";
$result = mysql_query($query);

Is there any way to grab each (id, first_name, last_name) as individual arrays without iterating through the recordset? Can I say something like:

$ids = field_to_array($result['id']);
$first_names = field_to_array($result['first_name']);
$last_names = field_to_array($result['last_name']);

As I said, in the past I've always simply built the arrays as needed, but an existing method would be handy.

user229044
  • 232,980
  • 40
  • 330
  • 338
humble_coder
  • 2,777
  • 7
  • 34
  • 46
  • 1
    You mean, to turn around the grid so that `$result['id']` contains, say, the 50 id's from the result set? – Pekka Nov 10 '10 at 21:28
  • You want the whole column as an array? – McKay Nov 10 '10 at 21:29
  • 1
    WITHOUT iterating through result set? If you don't hit each row returned how can you populate any array, much less a transposed one? – Jé Queue Nov 10 '10 at 21:49
  • @Pekka, McKay: Yes, that is exactly what I'm trying to do. As I said, I've been simply iterating through the recordset. I was hoping PHP had a native method to do such a thing. – humble_coder Nov 10 '10 at 22:19
  • @Xepoch: Yes, of course *some* method has to do it, I was simply curious as to whether PHP had a native mechanism. That's all. Thanks. – humble_coder Nov 10 '10 at 22:19

2 Answers2

1

mysql doesn't have that as a native function. you could always write your own..

function mysql_convert_cols($dataset) {
    foreach ($dataset as $row => $values) {
        foreach ($values as $column => $value) {
            $return[$$column][$row] = $value;
        }
    }
    return($return);
}

$resultConverted = mysql_convert_cols($result);
$id=$resultConverted['id'];
$firstName=$resultConverted['firstName'];
FatherStorm
  • 7,133
  • 1
  • 21
  • 27
  • Yup, that's basically what I've been doing. The only difference, however, I've only been concerned with one field at a time, and as such have set the function to process only a single field (as opposed to getting them all at once). – humble_coder Nov 10 '10 at 22:20
0

I'm not sure why do you need this , but you can do it like this :

$resultArray = array();  
while($row = mysql_fetch_array($result)){
       $resultArray[] = array(
          "id" =>  $row['id'],
          "firstName"=>$row['first_name'],
          "lastName"=>$row['last_name']
      );
    }

Check if values are in :

print_r($resultArray);

Then you can foreach or to do the for loop on values.

Conex
  • 832
  • 8
  • 17