我有一个包含问题I (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在文档的后面部分,echo没有为$q返回值/$a:
echo $x[1]谢谢,
发布于 2013-07-03 06:03:53
看起来问题在于您每次都要在循环中重新设置$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数组。
https://stackoverflow.com/questions/17436510
复制相似问题