1

How can I use foreach multiple times?

<?php
    $query =  $db->query('SELECT tbl_stok.id_stok,
        tbl_stok.id_provinsi,
        tbl_stok.id_kabupaten,
        tbl_stok.tanggal,
        tbl_stok.mie_instan,
        tbl_stok.beras,
        tbl_stok.telur
        FROM `tbl_stok` INNER JOIN tbl_wilayah ON tbl_stok.id_provinsi = tbl_wilayah.id_user
    ');
    $query->fetchAll;
?>

I want to use the first foreach to show the data tables:

<?php foreach($query as $row){
    echo $row['beras'];
}?>

Then I want to use the second foreach for chart:

<?php foreach($query as $row){
    echo $row['telur'];
}?>

However, this foreach works only once.

1
  • You can make script work faster by using only one for instead of two foreach. Please see updated answer for more clarification. Commented Nov 11, 2016 at 10:23

2 Answers 2

2

You can do this:

1) save your data to an array.

foreach($query as $row){
    $data[]= $row;
}

2) use your array in every loop you want as many time you want

foreach($data as $row){
    echo $row['beras'];
}

foreach($data as $row){
    echo $row['telur'];
}
Sign up to request clarification or add additional context in comments.

Comments

1

Use foreach only once and store all values you need, like this:

<?php 
   $beras_array = array();
   $telur_array = array();
   foreach($query as $row){
      $beras_array[] = $row['beras'];
      $telur_array[] = $row['telur'];
   }

  //you can use `for` explained later instead of two `foreach`
   foreach($beras_array as $b){
      echo $b;
   }
   foreach($telur_array as $t){
      echo $t;
   }

   //With this method you can also use only one for instead of two foreach
   $limit = count($beras_array);
   for($i=0; $i<$limit; $i++){
      echo $beras_array[$i];
      echo $telur_array[$i];
   }
?>

I hope it helps

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.