1

FROM array with no key:

$array = array('apple','bee','carrot','dragon','elephant')

To

$newarray = ($apple,$bee,$carrot,$dragon,$elephant)

Why: I want to create flexible function to get fields from a mysql db, like this:

<?php
$query = "SELECT ".$array." FROM table";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
        extract($row);
        echo $newarray;
}
?>

So I could:

  • SELECT apple, bee, carrot and echo $apple, $bee and $carrot
  • SELECT bee, carrot, elephant and echo $bee, $carrot, and $elephant
  • or whatever.
Leo
  • 580
  • 7
  • 22
  • What's wrong with `echo $row['apple'], $row['bee'], $row['carrot']`? – Frank Farmer Aug 31 '12 at 18:11
  • Nothing wrong, but how would I convert `$array = array('apple','bee','carrot')` to `$row['apple'], $row['bee'], $row['carrot']` – Leo Aug 31 '12 at 18:13

2 Answers2

3

Why don't you just fetch an associative array from the database and then use the key in the associative array like this:

// assume field names are 'apple', 'bee', 'carrot', etc.
while($row = mysql_fetch_assoc($result)){    
    foreach($row as $key => $value) {
        // this will set variables as $apple, $bee, $carrot, etc.
        $$key = $value;
    }
}

Of course this is not all that practical if you get more than one row in your result set, as the variables would just get overwritten.

The key to what you are wanting to do is the use of the variable variable ($$key in this case)

Oh yeah, you should also not be using mysql_* functions but rather mysqli_* or PDO.

Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • Will try this. I read about mysqli instead mysql, but I didn't got it right yet! Thanks! – Leo Aug 31 '12 at 18:16
  • Maybe this `$$key` and `${$value}` are the same? – Leo Aug 31 '12 at 18:49
  • @Leo The concept of using variable variables is the same. It seemed from the discussion that you wanted the names of the DB fields to be the variable names, in which case you would use the keys. If you really wanted to reference variables with the same name as your database values, then using variable variables on the value names would get you what you want. – Mike Brant Aug 31 '12 at 18:52
  • 1
    Actually I was trying to handle the array typed in a function to call properly the mysql db. Thank you very much, Mike Brant! You were very helpful! Now I'll enforce to learn mysqli! – Leo Aug 31 '12 at 19:03
0
foreach($array as $value){
    $newarray[] = ${$value};
    //Edited: maybe you'll need to reset the array after use it
    unset($newarray);
}

Got it!

Thanks all!

Leo
  • 580
  • 7
  • 22