1

I have a array and i use two foreach but I be only able to print the first foreach.

$test = $db->query("SELECT * FROM Test"); foreach ($test as $readTest) { echo $readTest["col1"]; } foreach ($test as $readTest) { echo $readTest["col2"]; } 

and I try with this:

$test1 = $test; $test2 = $test; 

I expect the output of $readTest["col1"] and $readTest["col2"], but the actual output is $readTest["col1"]

6
  • I don't understand. Just put the echo from the 2nd foreach inside the echo from the first foreach? Commented Jul 15, 2019 at 19:54
  • You used to have to reset() between foreach calls, (there is an internal cursor in the array that needed resetting) I think this changed, but what version of PHP is this? Commented Jul 15, 2019 at 20:00
  • few questions that'll really help see the issue. 1) what is the table structure of Test? 2) what does echo '<pre>'. print_r($test, 1) .'</pre>' output? 3) why are you looping the same thing twice.. why not one foreach loop echoing the values? At the moment they both start at 1, loop through then start again. Much more efficient to use one loop. Commented Jul 15, 2019 at 20:55
  • @Slabgorb that sounds ancient.. pre-5.4 stuff Commented Jul 15, 2019 at 20:55
  • @treyBake becauae i use in different lines Commented Jul 16, 2019 at 8:11

2 Answers 2

0

Use #fetchAll to get all your result in a conventional array. You will then be able to loop on them multiple times.

Sign up to request clarification or add additional context in comments.

Comments

0

Why use array, when you can print this way:

$test = $db->query("SELECT * FROM Test"); while($PrintTest = $test->fetch_object()) { echo $PrintTest->col1; echo $PrintTest->col2; } 

Even if you want to use Arrays, you can do something like this:

$Array1 = array(); $Array2 = array(); $test = $db->query("SELECT * FROM Test"); while($PrintTest = $test->fetch_object()) { $Array1[] = $PrintTest->col1; $Array2[] = $PrintTest->col2; } 

And then, you can run through the array with For or Foreach

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.