Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a mysql table with questions IDs (q_ID) and answers (a_answer). I want to use this data to populate some html later in the doc. Some of the data is separated by '|' and I want to use switch to filter. I am having trouble accessing the data by key. It works within while loop, but I need it outside.

$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

Later in the doc, echo does not return value/$a for $q:

 echo $x[1]

Thanks,

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

It looks like the problem is that you are re-setting $x every time through the loop. The following would likely be a better solution:

$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;

};
};

Edit: To create a one-dimensional array, do the following:

$x[$q] = $a;

You need to do that in the while loop and still declare the $x array before the while loop.

share|improve this answer
 
that works but returns in an array with an array. I was hoping to avoid that. print_r is 0] => Array ( [4] => 8 ) [1] => Array ( [5] => 6 ) [2] => Array ( [6] => male ) [3] => Array ( [7] => 77777 ) –  Marr Madden Jul 2 at 23:06
 
Well, how else are you going to store multiple rows of data in a variable if you don't use an array? You need to do something. You can create a one-dimensional array, if you want. –  HartleySan Jul 3 at 3:17
 
how would I create a one dimensional? –  Marr Madden Jul 3 at 4:09
 
Excellent! You make it look so easy - I've been struggling with this for hours. –  Marr Madden Jul 3 at 5:47
 
Well, I have lots of practice. I struggled with the same sorts of things at first. You'll get used to it. –  HartleySan Jul 3 at 12:39
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.