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"]

treyBake
  • 6,440
  • 6
  • 26
  • 57
  • I don't understand. Just put the echo from the 2nd foreach inside the echo from the first foreach? – GrumpyCrouton Jul 15 '19 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? – Slabgorb Jul 15 '19 at 20:00
  • few questions that'll really help see the issue. 1) what is the table structure of `Test`? 2) what does `echo '
    '. print_r($test, 1) .'
    ' 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.
    – treyBake Jul 15 '19 at 20:55
  • @Slabgorb that sounds ancient.. pre-5.4 stuff – treyBake Jul 15 '19 at 20:55
  • @treyBake becauae i use in different lines – Fırat Kaya Jul 16 '19 at 08:11
  • @FıratKaya what do you mean? o.O they'll both be row 1 – treyBake Jul 16 '19 at 08:16

2 Answers2

0

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

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