使用while循环函数将信息存储在数组中

时间:2012-07-05 12:39:49

标签: php arrays function

如何将信息存储在数组中?

我正在尝试从数据库中获取信息,然后将HTML代码存储在数组中。

这可能吗?如果是这样的话?

function echothatshit() {
    $sqll=mysql_query("select id,data from produkter where weight='1'");
    $alla = array();    
    while($row=mysql_fetch_array($sqll))
    {
        $idd=$row['id'];
        $data=$row['data'];
        $alla[] = '<option value="'.$idd.'">'.$data.'</option>';
    }
}

$test2 = echothatshit();                       
echo $test2;

4 个答案:

答案 0 :(得分:4)

你最后需要return $alla;函数,也不能直接回显数组,你需要循环它。

答案 1 :(得分:2)

function echothatshit() {
    $sqll=mysql_query("select id,data from produkter where weight='1'");
    $alla = array();
    $i=0;    
    while($row=mysql_fetch_array($sqll))
    {
        $idd=$row['id'];
        $data=$row['data'];
        $alla[$i] = '<option value="'.$idd.'">'.$data.'</option>';
        $i++;
    }
    $yourVariable="";
    for ($j=0;$j<$i;$j++)
    {
        $yourVariable.=$alla[$j];
    }
    return $yourVariable;
}

$test2 = echothatshit();                       
echo $test2;

答案 2 :(得分:1)

为什么不将$alla作为字符串,即(通过一些格式化/重命名/简化):

function getProductsHTML()
{
  $sql = mysql_query("select id,data from produkter where weight='1'");
  $html = '';

  while($row = mysql_fetch_array($sql))
    $html .= '<option value="'.$row['id'].'">'.$row['data'].'</option>'."\n";

  return $html;
}

echo getProductsHTML();

答案 3 :(得分:0)

function echothatshit() {
$sqll=mysql_query("select id,data from produkter where weight='1'");
$alla = array();    
while($row=mysql_fetch_array($sqll))
    {
$idd=$row['id'];
$data=$row['data'];
$alla[] = '<option value="'.$idd.'">'.$data.'</option>';
    }
return $alla;
}
$test2 = echothatshit();                       
echo $test2;

如果你想让$ test2得到数组$ alla,那就返回吧。 然后,为了正确打印数组,请使用

echo "<pre>";
print_r($test2);
echo "</pre>";