문제

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.
도움이 되었습니까?

해결책 2

foreach($array as $value){
    $newarray[] = ${$value};
    //Edited: maybe you'll need to reset the array after use it
    unset($newarray);
}

Got it!

Thanks all!

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top