how to store values of foreach as array - php

<?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 :)

Related

PHP combine matching rows from associative arrays from sql and display results in html

I have 2 results set
$result_a = #pg_query($rquery_a);
$result_b = #pg_query($rquery_b);
I have 2 arrays to host and display the data on an html page:
$datas_a = array();
$datas_b = array();
$datas_a gets this data:
$i=0;
while ($row = #pg_fetch_assoc($result_a)){
$datas_a[$i] = array('s1' => $row['salle'],
'duree_occu' => $row['duree_resa']);
$i++;
}
and $datas_b gets this data:
$i=0;
while ($row = #pg_fetch_assoc($result_b)){
$datas_b[$i] = array('s1' => $row['salle'],
'duree_cours' => $row['duree_cours']);
$i++;
}
From these 2 existing arrays with same number of rows and same keys, I would like 3 columns, 1 column is the same for both arrays ($datas_a and $datas_b), the second column is from $datas_a and the third column is from $datas_b
It currently looks like this for $datas_a
$datas_a
It currently looks like this for $datas_b
$datas_b
It should look like this
merging columns
Now, I have used
$dataComb = array_merge($datas_a, $datas_b);
but it puts one array on top of the other while I would like to just add a column
try
$i=0;
foreach ($datas_a as $data) {
$dataComb[$i]["s1"] = $data["s1"];
$dataComb[$i]["duree_resa"] = $data["duree_resa"];
$i++;
}
$i=0;
foreach ($datas_b as $data) {
$dataComb[$i]["duree_cours"] = $data["duree_cours"];
$i++;
}
Edit - 2021-08-20
Or for something more robust given it's a basic way I only know to do this
$datas_a = array(); // associative array
$datas_b = array();
$dataComb = []; // indexed array
$i=0;
while ($row = #pg_fetch_assoc($result_a)){
$datas_a[$i] = array('s1' => $row['salle'],
'duree_resa' => $row['duree_resa']);
$i++;
}
$i=0;
while ($row = #pg_fetch_assoc($result_b)){
$datas_b[$i] = array('s1' => $row['salle'],
'duree_cours' => $row['duree_cours']);
$i++;
}
$i=0;
if($a>=$b){
foreach($datas_a as $dataa) {
$dataTmp[$i][0] = $dataa["s1"];
$dataTmp[$i][1] = $dataa["duree_resa"];
foreach($datas_b as $datab) {
if($dataa["s1"] == $datab["s1"] ){
$dataTmp[$i][2] = $datab["duree_cours"];
}
}
$i++;
}
}
elseif($a<$b){
foreach($datas_b as $datab) {
$dataTmp[$i][0] = $datab["s1"];
$dataTmp[$i][1] = $datab["duree_resa"];
foreach($datas_a as $dataa) {
if($datab["s1"] == $dataa["s1"] ){
$dataTmp[$i][2] = $dataa["duree_cours"];
}
}
$i++;
}
}
$nb_lig = $a>=$b ? $a : $b;
for ($row=0; $row<=$nb_lig; $row++) {
$dataComb[$row]["s1"] = $dataTmp[$row][0];
$dataComb[$row]["duree_resa"] = $dataTmp[$row][1];
$dataComb[$row]["duree_cours"] = $dataTmp[$row][2];
}
And there is $dataComb as an associative array that combines the data from previous arrays with matching records
foreach ($dataComb as $data){
echo '<tr>';
echo '<td>'.$data["s1"].'</td>';
echo '<td>'.$data["duree_resa"].'</td>';
echo '<td>'.$data["duree_cours"].'</td>';
echo '</tr>';
}

PHP Add New Line to Array Values Inside One Row and Column in Database Table

I managed to add multiple data in one column in the database, but now I need to display it with a new line in the browser so they don't stick with each other as I display them as an array in one column.
Here is my code:
if (isset($_GET['id']) && $_GET['id'] == 5) {
$subArray = array("StudentAnswer");
$subId6 = $db->get("answertable", null, $subArray);
foreach ($subId6 as $sub) {
$answers[] = $sub['StudentAnswer'] . "\n";
}
foreach ($answers as $row) {
$answers2 = explode("||", $row[0]);
foreach($answers2 as $row2){
$answers3 = $row2 . '\n';
}
}
$db->where('AccessId', $_GET['token']);
$db->where('StudentAnswer', $answers3);
$subId8 = $db->get("answertable");
if ($subId8) {
echo json_encode($subId8);
}
}
You are overriding $subId6 after getting its content. Try to fetch the table $rows in a new variable and the extract the content from it, like the code below.
<?php
// Example of $subId6 content
$subId6 = array(["StudentAnswer" => ["Answer 1\nAnswer 2\nAnswer 3"]], ["StudentAnswer" => ["Answer 1\nAnswer 2\nAnswer 3"]]);
// Fetch rows
foreach ($subId6 as $sub) {
$rows[] = $sub['StudentAnswer'];
}
// Decode rows
foreach($rows as $row) {
$answers = explode("\n", $row[0]);
echo "New answers: \n";
// Split answers in single answer
foreach ($answers as $answer)
echo "$answer \n";
echo "\n";
}
You will have a list of all the answers split for table rows
If you want a string of answers seperated by a space then simply do
if (isset($_GET['id']) && $_GET['id'] == 5) {
$subId6 = $db->get("answertable");
foreach ($subId6 as $sub) {
$answers .= $sub['StudentAnswer'] . ' ';
}
$answers= rtrim($answers, ' '); //remove last space in case thats an issue later
$db->where('AccessId', $_GET['token']);
$db->where('StudentAnswer', $answers);
$subId8 = $db->get("answertable");
if ($subId8) {
echo json_encode($subId8);
}
}

using foreach multiple times

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

Making a dynamic array

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.

What is the problem with this foreach loop?

why doesnt this array work? What do I do wrong? The result of my foreach loop is always either empty or just some weird numbers and signs. So what is wrong with my foreach loop?
$array = array();
while($row = mysqli_fetch_array($result)) {
if(!empty($row["some"])) {
$array["some"] = $row["some"];
$array["some2"] = $row["some2"];
}
}
foreach($array as $property=>$value) {
echo '<p>'.$value["some"].' - '.$value["some2"].'</p>'; }
$array will have only two properties, some and some2. Therefore your foreach loop doesn't make any sense. The foreach will loop two times, the first time with this:
$property = 'some';
$value = $row["some"];
and the second with this:
$property = 'some2';
$value = $row["some2"];
You will have to make $array multidimensional in your first loop by doing this:
while($row = mysqli_fetch_array($result)) {
$new = array();
if(!empty($row["some"])) {
$new["some"] = $row["some"];
$new["some2"] = $row["some2"];
$array[] = $new;
}
}
or shorter:
while($row = mysqli_fetch_array($result)) {
if(!empty($row["some"])) {
$array[] = array('some' => $row["some"],
'some2' => $row["some2"]);
}
}
$array["some"] and $array["some2"] are specific array elements. You are overwriting them every iteration of your while loop.
Not sure what you're trying to actually accomplish but I think possibly this is what you want:
$array = array();
while($row = mysqli_fetch_array($result)) {
if(!empty($row["some"])) {
$array["some"][] = $row["some"];
$array["some2"][] = $row["some2"];
}
}
foreach($array["some"] as $property=>$value) {
echo '<p>'.$value.' - '.$array["some2"][$property].'</p>';
}
or
$array = array();
while($row = mysqli_fetch_array($result)) {
if(!empty($row["some"])) {
$array[] = array('some' => $row["some"],
'some2' => $row["some2"]);
}
}
foreach($array as $property=>$value) {
echo '<p>'.$value['some'].' - '.$value['some2'].'</p>';
}
or similar...kinda depends on what you're ultimately trying to accomplish...
This doesn't explain the weird numbers and signs, but you are overwriting $array['some'] and $array['some2'] on each loop iteration.
Instead, try this:
while($row = mysqli_fetch_array($result)) {
if(!empty($row["some"])) {
$array[] = array("some"=>$row['some'], "some2"=>$row['some2']);
}
}
$array[] = array('some' => $row["some"], 'some2' => $row["some2"]);
But it would be better to retrieve only these columns.
Emil has the right answer :D. I love how people post so fast on here lol.

Categories