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.
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'];
}
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
Related
I have this long foreach code I want to use to get folders and subfolders ids in order to be able to delete them.
// first foreach code
$idsToDelete = $this->entityManager->getRepository(Folders::class)
->findBy(['parentId'=>$postId]);
foreach ($idsToDelete as $d){
$postId = $d->getId(); echo $postId.', ';
//second foreach code in first foreach
$idsToDelete = $this->entityManager->getRepository(Folders::class)
->findBy(['parentId'=>$postId]);
foreach ($idsToDelete as $d){
$postId = $d->getId(); echo $postId.', ';
//third foreach code in second foreach
$idsToDelete = $this->entityManager->getRepository(Folders::class)
->findBy(['parentId'=>$postId]);
foreach ($idsToDelete as $d){
$postId = $d->getId();
echo $postId.', ';
//forth foreach code in third foreach
$idsToDelete = $this->entityManager->getRepository(Folders::class)
->findBy(['parentId'=>$postId]);
foreach ($idsToDelete as $d){
$postId = $d->getId(); echo $postId.', ';
//fith foreach code in forth foreach
$idsToDelete = $this->entityManager->getRepository(Folders::class)
->findBy(['parentId'=>$postId]);
foreach ($idsToDelete as $d){
$postId = $d->getId(); echo $postId.', ';
}
}
}
}
}
the problem with this code is that, I will have to write foreach statement for each iteration I want to make.
How do I write a simple loop or function to do this once.
Thanks.
You can put this inside a method and make your method recursive since there could be dynamic nested calls and we wouldn't be sure how many static foreachs to write.
Snippet:
<?php
public function deleteIDs($postId){
$idsToDelete = $this->entityManager->getRepository(Folders::class)
->findBy(['parentId' => $postId]);
foreach ($idsToDelete as $d){
$currPostId = $d->getId(); echo $currPostId.', ';
$this->deleteIDs($currPostId);
}
}
<?php
$samgri = $this->crud_model->get_puja_samagri_by_puja_order($param1,$param);
foreach ($samgri as $row){
$puja_samagri = $row['puja_samagri'];
}
$puja_sam = explode(',', $puja_samagri);
foreach ($puja_sam as $samagri_id){
$samg = $this->crud_model->get_puja_samagri_by_id($samagri_id);
}
if(sizeof($samg) == 0){
echo '<h5 style = "text-align:center">No samagari available</h5>';
}else{
foreach ($samg as $row){
?>
but it was fetching only the last record not total records
You should add brackets after the array name like:
<?php
$samgri = $this->crud_model->get_puja_samagri_by_puja_order($param1,$param);
//Declare the arrays
$puja_samagri = new array();
$samg = new array();
foreach ($samgri as $row){
$puja_samagri[] = $row['puja_samagri'];
}
$puja_sam = explode(',', $puja_samagri);
foreach ($puja_sam as $samagri_id){
$samg[] = $this->crud_model->get_puja_samagri_by_id($samagri_id);
}
if(sizeof($samg) == 0){
echo '<h5 style = "text-align:center">No samagari available</h5>';
}else{
foreach ($samg as $row){
?>
It will use the automatic int position (from 0 going up untill you have all the results). Also it might be a good idea to declare them as arrays before using them.
You have to take array after every foreach veriable as like follows :
<?php
$samgri = $this->crud_model->get_puja_samagri_by_puja_order($param1,$param);
foreach ($samgri as $row){
$puja_samagri[] = $row['puja_samagri'];
}
$puja_sam = explode(',', $puja_samagri);
foreach ($puja_sam as $samagri_id){
$samg[] = $this->crud_model->get_puja_samagri_by_id($samagri_id);
}
if(sizeof($samg) == 0){
echo '<h5 style = "text-align:center">No samagari available</h5>';
}else{
foreach ($samg as $row){
?>
Hope this will help you :)
I have the following code that should select all the users in the relevant table in my database:
$hof = mysql_query("SELECT * FROM users");
$name = array();
$website = array();
$i=0;
while($result = mysql_fetch_array($hof)){
$name[$i] = $result['company'];
$website[$i] = $result['website'];
}
$i++;
I want to echo out the names and websites of all in the html section of my script (below the php) which will be a Hall of Frame of sorts. How would i do is? The fact that i do not know the size of the array deters me.
Usually, if i knew the size, i would so something like:
<?php echo $name[1];?>
<?php echo $name[2];?>
//and so on
Many thanks in advance. P.S. I plan to move across to MySQLi when i have the functionality of the website sorted first on localhost. Cheers
Your $i++; statement should be inside while loop
while($result = mysql_fetch_array($hof)){
$name[$i] = $result['company'];
$website[$i] = $result['website'];
$i++;
}
Better You do it like this,
$rows = array();
while($result = mysql_fetch_assoc($hof)){
$rows[] = $result;
}
and you echo them like this,
<?php
$len = count($name);
for($i=0;$i<$len;$i++){
echo $name[1];
}
?>
And for the alternative method use this,
<?php
foreach($rows as $row){
echo $row['name']; // use $row['website'] to echo website.
}
?>
foreach($name as $key=>$value){
echo $name[$key];
echo $website[$key];
}
Also there no need to take $i++, you can use following way
while($result = mysql_fetch_array($hof)){
$name[] = $result['company'];
$website[] = $result['website'];
}
See array in manual
First off the $i++ should be inside the loop.
To output them all, you could use implode(), or maybe foreach.
First, take your data into array
$data = array();
$sql = "SELECT * FROM users";
$res = mysql_query($sql) or trigger_error(mysql_error()."[$sql]");
while($row = mysql_fetch_array($res)){
$data[] = $row;
}
then use it anywhere you wish, say, in the template:
<ul>
<? foreach($data as $row): ?>
<li><?=$row['company']?></li>
<? endforeach ?>
</ul>
How about:
foreach ($name as $val)
{
echo $val;
}
you can use mysql_num_rows() to know the number of results returned by your query
$arrarySize = mysql_num_rows($hof);
THE ANSWER THAT WORKED FOR ME BASED ON AN ANSWER GIVEN
while($post = mysql_fetch_array($tags)) {
$push = explode(',', $post['tags']);
$array = array_merge($array, $push);
}
So I'm trying to display tags from my data base and make links out of them like this:
<?
$tags = mysql_query( 'SELECT tags FROM `Table`');
$array = array();
while($post = mysql_fetch_array($tags)) {
$push = explode(',', $post['tags']);
array_push($array, $push);
}
foreach ($array as $value) {?>
<? echo $value?>
<? }
?>
However all I get back is
Array
Where I should be having at least three lines as was previously produced by
<?
$tags = mysql_query( 'SELECT tags FROM `Table`');
while($post = mysql_fetch_array($tags)) {
$array = explode(',', $post['tags']);
foreach ($array as $value) {?>
<? echo $value?>
<? }
}
?>
The code being called looks like this:
tag1, tag2, tag3
Tried
while($post = mysql_fetch_array($tags)) {
$push = explode(',', $post['tags']);
array_merge($array, $push);
}
foreach ($array as $value) {?>
<? echo $value?>
now foreach doesn't return a value
Use array_merge(), because array_push() will push the output of explode(), which is an array, as a whole to the array in the first argument, creating a jagged array.
As for your edit, this works:
$array = array_merge($array, $push);
foreach ($array as $value)
{
echo '' . $value . '';
}
Please note that array_merge() (contrary to array_push(), gotta love the consistency) does not alter the array passed as its first argument, so you'll have to store the return value which I do on the first line ($array = ...).
While outputting to HTML, you also might want to put a $value = htmlentities(trim($value)); in the foreach loop.
I want to echo the values of all arrays that has been returned from a search function. Each array contains one $category, that have been gathered from my DB. The code that I've written so far to echo these as their original value (e.g. in the same form they lay in my DB.) is:
$rows = search($rows);
if (count($rows) > 0) {
foreach($rows as $row => $texts) {
foreach ($texts as $idea) {
echo $idea;
}
}
}
However, the only thing this code echoes is a long string of all the info that exists in my DB.
The function, which result I'm calling looks like this:
function search($query) {
$query = mysql_real_escape_string(preg_replace("[^A-Za-zÅÄÖåäö0-9 -_.]", "", $query));
$sql = "SELECT * FROM `text` WHERE categories LIKE '%$query%'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows['text'] = $row;
}
mysql_free_result($result);
return $rows;
}
How can I make it echo the actual text that should be the value of the array?
This line: echo $rows['categories'] = $row; in your search function is problematic. For every pass in your while loop, you are storing all rows with the same key. The effect is only successfully storing the last row from your returned query.
You should change this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
echo $rows['categories'] = $row;
}
mysql_free_result($result);
return $rows;
to this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
Then when you are accessing the returned value, you could handle it like the following...
foreach ($rows as $key => $array) {
echo $array['columnName'];
// or
foreach ($array as $column => $value) {
echo $column; // column name
echo $value; // stored value
}
}
The problem is that you have a multi-dimensional array, that is each element of your array is another array.
Instead of
echo $row['categories'];
try print_r:
print_r($row['categories']);
This will technically do what you ask, but more importantly, it will help you understand the structure of your sub-arrays, so you can print the specific indices you want instead of dumping the entire array to the screen.
What does a var_dump($rows) look like? Sounds like it's a multidimensional array. You may need to have two (or more) loops:
foreach($rows as $row => $categories) {
foreach($categories as $category) {
echo $category;
}
}
I think this should work:
foreach ($rows as $row => $categories) {
echo $categories;
}
If this will output a sequence of Array's again, try to see what in it:
foreach ($rows as $row => $categories) {
print_r($categories);
}