PHP while循环输出到变量

时间:2016-07-09 20:25:31

标签: php

我有以下循环从数据库中获取数据......

$query = "SELECT id, metal, colour, value FROM data WHERE asset='gold' OR asset='silver' ORDER BY id DESC LIMIT 2";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_assoc($result)){
    echo $row['metal'] . " is " . $row["colour"] . "<br />";
    echo $row['metal'] . " is worth " . $row["value"] . "<br />";
}

输出以下内容:

silver is grey
silver is worth 50
gold is yellow
gold is worth 100

以下内容:

echo $row['metal'] . " is " . 

和...

echo $row['metal'] . " is worth " . 

...只是用于测试并帮助解释我的问题。我如何将输出放入变量中:

$silverColour = grey
$silverValue = 50
$goldColour = yellow
$goldValue = 100

非常感谢

5 个答案:

答案 0 :(得分:3)

您可以使用{},试试这个:

  ${$row['metal'].'Color'} = $row["colour"]; 
  ${$row['metal'].'Value'}= $row["value"];

另一种更简单的方法是使用数组的键和值。保持密钥为

 $array[row['metal'].'Color']= $row["colour"];
 $array[row['metal'].'Value']= $row["value"];

迭代数组并打印/访问值。

答案 1 :(得分:1)

$query = "SELECT id, metal, colour, value FROM data WHERE asset='gold' OR asset='silver' ORDER BY id DESC LIMIT 2";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_assoc($result)){
 ${$row['metal'].'color'} = $row['metal'];
 ${$row['metal'].'value'} = $row['value'];
}

答案 2 :(得分:0)

可以向您展示一种做法的hackish方式,但我想向您展示使用数组的不同方法:

$query = "SELECT id, metal, colour, value FROM data WHERE asset='gold' OR asset='silver' ORDER BY id DESC LIMIT 2";
$result = mysqli_query($connect, $query);
$metals = array();
while ($row = mysqli_fetch_assoc($result)){
    $metals[$row['metal']] = array('color' => $row['color'], 'value' => $row['value']);
}

在此之后,你将拥有一系列各种金属(var_dump($metals);)。

像这样访问它:

$metals['gold']['color'];
$metals['gold']['value'];

如果你真的坚持使用你的方法,

$query = "SELECT id, metal, colour, value FROM data WHERE asset='gold' OR asset='silver' ORDER BY id DESC LIMIT 2";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_assoc($result)){
    ${$row['metal'] . 'Color' } = $row['color'];
    ${$row['metal'] . 'Value' } = $row['value'];
}

应该有用。

答案 3 :(得分:0)

$color= array();
$values= array();
while (($row = mysqli_fetch_assoc($result)) {
   $color[] = (string) $row["colour"];
   $color[] = (string) $row["value"];
}

// If you don't want an array, but a string instead, use implode:

$color= implode(' ', $color)
$values= implode(' ', $values)

答案 4 :(得分:0)

以这种方式修改代码:

$values = [];
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_assoc($result)){
    echo $row['metal'] . " is " . $row["colour"] . "<br />";
    echo $row['metal'] . " is worth " . $row["value"] . "<br />";
    $values[$row['metal']] = $row;
}

然后您可以访问$values数组中的值:

echo '$silverColour = '. $values['silver']['colour'];
echo '$silverValue = '. $values['silver']['value'];
echo '$goldColour = '. $values['gold']['colour'];
echo '$goldValue = '. $values['gold']['value'];