我有一个带有问题ID(q_ID)和答案(a_answer)的mysql表。我想使用这些数据在文档中稍后填充一些html。一些数据用'|'分隔我想用switch来过滤。我无法通过密钥访问数据。它在while循环中工作,但我需要在外面。
$getData="SELECT a_answer, q_ID FROM answers ";
$result = mysqli_query($connected, $getData);
while($row = mysqli_fetch_assoc($result))
{
$arAnswer = explode('|', $row['a_answer']);
//catagorize by number of values
$arrayCount = count($arAnswer);
switch ($arrayCount)
{
case 1: //short data, no separators
//make array for ID and answer
$q = $row['q_ID'];
$a = $arAnswer[0];
$x = array($q=>$a);
break;
}; //END switch
}; //END while
稍后在doc中,echo不会为$ q返回值/ $ a:
echo $x[1]
谢谢,
答案 0 :(得分:0)
看起来问题是你每次循环都要重新设置$ x。以下可能是更好的解决方案:
$getData="SELECT a_answer, q_ID FROM answers ";
$result = mysqli_query($connected, $getData);
$x = array(); // Added this.
while($row = mysqli_fetch_assoc($result))
{
$arAnswer = explode('|', $row['a_answer']);
$arrayCount = count($arAnswer);
switch ($arrayCount)
{
case 1:
$q = $row['q_ID'];
$a = $arAnswer[0];
$x[] = array($q=>$a); // Add [] after $x to push array($q=>$a)
// onto the end of the $x array.
// You can also use array_push, but
// the technique here is quicker.
break;
};
};
编辑:要创建一维数组,请执行以下操作:
$x[$q] = $a;
您需要在while循环中执行此操作,并在while循环之前仍然声明$ x数组。