PHP foreach loop through multidimensional array - php

I have an multidimensional array, how can I use it? I want to use each separate array in a for loop.
What I want to achive is to be able to put each part in my database like
entry in db no. 0 -> 1 and 4
entry in db no. 1 -> 5 and 6
entry in db no. 2 -> 1 and 4 and 5 and 6
I have this code:
<?php
print_r($calculatie_id);
for ($i=0; $i<=3; $i++)
{
?>
<tr>
<td>
<?php
foreach ($calculatie_id[$i] as $value)
{
echo $value;
}
?>
print_r($calculatie_id); gives
Array ( [0] => Array ( [0] => 4 [1] => 6 ) [1] => Array ( [0] => 1 [1] => 5 ) [2] => Array ( [0] => 5 [1] => 6 ) [3] => )
But when using the foreach I only get 46
Some extra information:
This array is created by an multiple select in an for loop. Any other suggestions are welcome.
for ($i=0; $i<=$aantal_regels_corr; $i++)
{
?>
<tr>
<td>
<?php
// maak select name
$calculatie_id = 'calculatie_id'.$i;
// rest van formulier
if($error_vergeten[$i] == "ja"){ $error_omschr = $error_omschr_vergeten[$i]; include('includes/input_error.php'); } ?> <textarea rows="7" cols="80" name="omschrijving[]" /><?php echo $omschrijving[$i]; ?></textarea>
</td>
<td colspan="2">
<select multiple="multiple" width="50" size="7" name="<?php echo $calculatie_id ?>[]" style="width: 150px">
<?php
$sql_calc = "select id, naam, actief from sp_calculatie WHERE (offerte_id = '".$row['off_offerte']."' OR offerte_id = '".$offerte_id."') AND actief = 'ja' ORDER BY id ASC";
$res_calc = mysql_query($sql_calc,$con);
while ($row_calc = mysql_fetch_assoc($res_calc)){
?>
<option value="<?php echo $row_calc["id"] ?>"><?php if (empty($row_calc["naam"])) { echo $row_calc["id"]; } else { echo $row_calc["naam"]; } ?></option>
<?php } ?></select>
</td>
</tr>
<?php } ?>

foreach($calculatie_id as $inner_arr)
foreach($inner_arr as $value)
echo $value;
Edit: you should try to learn and understand what's going on here. Then, you can do whatever you want with the code I wrote. You said: gives 14561456 I want to use $calculatie_id0=14 $calculatie_id1=56 $calculatie_id2=1456 etc Then, you will have to do something like this:
foreach($calculatie_id as $index => $inner_arr){
echo "$calculatie_id$index = "
foreach($inner_arr as $value)
echo $value;
echo "<br/>";
}
Or you can create those variables you want (which does not make any sense for me):
foreach($calculatie_id as $index => $inner_arr){
${"calculatie_id$index"} = '';
foreach($inner_arr as $value)
${"calculatie_id$index"} .= $value;
echo ${"calculatie_id$index"}."<br/>";
}

Basically what you have is an array like this:
array(
array(
data
)
)
All you need is:
foreach($yourArray as $innerArray)
foreach($innerArray as $value)
echo $value;
That will output what you want. I'm not particularly sure why you're doing a for() loop then a foreach.

You need to nest your foreach loops (so you have a loop inside a loop)

You could try:
foreach ($calculatie_id as $key => $value) {
echo "$calculatie_id:".$key;
for ($i=0;$i<=count($value);$i++) {
echo $value[$i];
}
}

I don't understand why your original code snippet isn't working. Could it be the fact that $calculatie_id[3] is not an array?
I tried this:
<?php
$calculatie_id = array ( array(4,6), array(1,5), array(5,6), '' );
for ($i=0; $i<=3; $i++)
{
if(!is_array($calculatie_id[$i]))
continue;
echo "$i: ";
foreach ($calculatie_id[$i] as $value)
{
echo $value;
}
echo '<br/>';
}
And that prints:
0: 46
1: 15
2: 56

Many thanks for helping me out this far but all the examples I try to implement are not working.
I have been trying this script for over 2 weeks now. It seems I'm going all the wrong way.
I have put my code online at www.pws.nl/downloads/sp_offerte_add.rar. It must be easier then what I'm writing in the code right now.

Related

PHP Form keep input values together to create JSON list

I have a JSON list with conditions(items) and a color associated to every condition. I'm building a form to try to update the conditions, then return to the JSON format.
Example:
<?php
?>
$JSON_list = {
"FULL":"green",
"Half-Full":"amber",
"Quarter-Full":"amber",
"Empty":"red"
}
I json_decode() this list to turn it into a php array. Then iterate through it and display the values as inputs which can be edited.
<form action="updatedata.php" method="post">
<?php
foreach($JSON_list as $condition) {
foreach($condition as $item => $color){
?>
<input type="text" name="item[]" value="<?=$item;?>">
<select name="color[]">
<option selected="selected"><?=$color;?></option>
<option>green</option>
<option>amber</option>
<option>red</option>
</select>
<br>
<?php
};
};
};
?>
<input type="submit" value="Submit Conditions">
</form>
On submission of the form, the "items" & "colors" are stored in 2 different arrays separate from each other. I iterate through each of these arrays to obtain the new values, and then concatenate them into a JSON list again.
updatedata.php:
<?php
$num = count($_POST['item']);
$i = 1;
$subs = [];
foreach($_POST["item"] as $item){
$subs["item".$i] = $item;
$i++;
};
$c = 1;
foreach($_POST["color"] as $item){
$subs["color".$c] = $item;
$c++;
};
$submit_string = "";
$a = 1;
$comma = ",";
for($x = 0; $x < $num; $x++){
if($a == $num){
$comma = "";
};
$submit_string .= "\"".$subs["item".$a]."\":"."\"".$subs["color".$a]."\"".$comma;
$a++;
};
echo "{" . $submit_string . "}";
//Prints the JSON string "FULL":"green","Half-Full":"amber","Quarter-Full":"amber","Empty":"red"
?>
My problem occurs when the "item" input is submitted with nothing, if an item has a value of "" then I don't want this entry in the JSON list. I need to delete this entry, but also the "color" associated to that item.
Is there a way to link the "items" & "numbers" from the form so I can delete both entries??
I think there is maybe a bit more to your code you are not showing us, for example with the given structure of $JSON_list the 2 nested foreach loops you have to generate the HTML would not work. Here's what I did to get your code working:
$JSON_list needs quotes and a trailing semi-colon:
$JSON_list = '{
"FULL":"green",
"Half-Full":"amber",
"Quarter-Full":"amber",
"Empty":"red"
}';
Convert it to an array:
$array = json_decode($JSON_list, true);
Generate the HTML:
<?php foreach ($array as $item => $color) { ?>
<input type="text" name="item[]" value="<?php echo $item; ?>">
<select name="color[]">
<option selected="selected"><?php echo $color; ?></option>
<option>green</option>
<option>amber</option>
<option>red</option>
</select>
<br>
<?php } ?>
Next, if you dump out what you're getting back from a form submission, it gives you an idea of how to process it. Here's the output of print_r($_POST); after the form was submitted with the "HALF-FULL" text input blank:
Array
(
[item] => Array
(
[0] => FULL
[1] =>
[2] => Quarter-Full
[3] => Empty
)
[color] => Array
(
[0] => green
[1] => amber
[2] => amber
[3] => red
)
)
So now the relation between the 2 arrays is clear, and you can see we can use the array keys to map the elements of one to the other.
// We'll store our results in this new array
$submitted = [];
// Iterate over the first array elements
foreach ($_POST['item'] as $key => $value) {
// We only want to include item/colors that were non-blank,
// so check if we got an item here
if ($value) {
// OK it wasn't blank, so let's save the result, using
// the corresponding element from the color array
$submitted[$value] = $_POST['color'][$key];
}
}
// Now we have an array of our submitted data
// print_r($submitted);
// Array
// (
// [FULL] => green
// [Quarter-Full] => amber
// [Empty] => red
// )
// You should never try to construct a JSON string manually, just
// let PHP do it for you:
$newList = json_encode($submitted);
// echo $newList;
// {"FULL":"green","Quarter-Full":"amber","Empty":"red"}

Array multi-dimensional error PHP

<?php
$ctr = 0;
foreach($rows as $row){
?>
<input type="hidden" name="client<?php echo $ctr; ?>['client_id']" value="<?php echo $row['client_id']; ?>">
<input type="hidden" name="client<?php echo $ctr; ?>['transaction_id']" value="<?php echo $row['id']; ?>">
<input style="max-width: 100px;min-width:100px;" class="form-control right" type="text" name="client<?php echo $ctr;?>['amount']" value="" />
<?php
}
?>
Update: I have included the form where $_POST coming from.
This it the output of print_r ($_POST);:
Array
(
[client0] => Array
(
['client_id'] => 1
['transaction_id'] => 1
['amount'] => 1000
['mode'] => cash
)
[client1] => Array
(
['client_id'] => 2
['transaction_id'] => 5
['amount'] => 600
['mode'] => cash
)
[client2] => Array
(
['client_id'] => 3
['transaction_id'] => 6
['amount'] => 200
['mode'] => cash
)
[save] =>
)
When I try writing this: echo $_POST['client0']['amount'];.
I'm expecting an output of 1000
but it gives me an error like this: Notice: Undefined index: amount.
So guys can you please tell me whats wrong with my code.TIA
Compare the print_r output carefully. One key is given as client0 while the next is given as 'amount'. That's because your key is actually 'amount', not amount. Because you're including unnecessary quotes in your HTML. Fix your HTML so the input name becomes:
name="client0[amount]"
(Or alternatively address the key as $_POST['client0']["'amount'"].)
And while you're at it, you may want to rename your fields to:
name="clients[0][amount]"
Because then you can simply traverse the data using:
foreach ($_POST['clients'] as $client) {
echo $client['id'], $client['amount'], ..;
}
Which is much more readable and sane.
You should use
echo $_POST['client0']['amount'];
You are using wrong variable amount_id just check it out your array having variable is "amount" so change the variable name like bellow
echo $_POST['client0']['amount'];
I hope this will help you.
Try this way ..
foreach ($_POST['client0'] as $val) {
echo $val['amount'] ;
}

php get the text into an array list

I have an array in the database. When I used print_r($variable_name), I got the array like this
Array
(
[0] => Array
(
[attribute_name] => Disk space,Color,Processor
)
)
So to get the value of attribute_name I tried this
foreach($attributes_name as $key=>$val) {
echo $val['attribute_name'];
}
Here I got the result like Disk space,Color,Processor. But I want the result should come like a list
<li>Disk Space</li>
<li>Color</li>
<li>Processor</li>
So can someone tell me how to do this?
Try this :
<?php
$arr = array(array("attribute_name" => "Disk space,Color,Processor"));
foreach($arr as $val) {
$resultArr = explode(",",$val['attribute_name']);
foreach($resultArr as $value){
echo "<li>".$value."</li>";
// Add id in li
echo "<li id='".str_replace(" ","_", strtolower($value))."'>".$value."</li>";
}
}
?>

how to echo multidimension array using php

I have the following array, I need to display the names on a form.
How can I do this via foreach() loop?
What I am trying is:
Array
(
[0] => Array
(
[to_user_name] => John
)
[1] => Array
(
[to_user_name] => Mike
)
)
foreach( $myArray as $subArray ) {
echo $subArray["to_user_name"];
}
It's not clear how you want to use those values in your form, but just echo the values wherever you'd need them, e.g.,
foreach( $myArray as $subArray ) {
echo "<input type=\"text\" name=\"user_name\" value=\"" . $subArray["to_user_name"] . "\">";
}
I was treating it like a single array and then i realized it is a multidimensino array and the following worked, i hope this helps someone else too
foreach ($messages->getMessage('recipient_names') as $section => $items ){
foreach ($items as $key => $value){
echo "$value, ";
}
}
to see the content you can use
print_r($your_array);
For developing purpose you need to use for/foreach loop
foreach($your_array as $array_temp)
{
foreach($array_temp as $item)
{
echo $item;
}
}

Store multidimensional array from JQuery Dropdown checklist in database in string form using loop

I want to store an array of checklist into a string in a database. Below this is the code in the interface which display a list of room with a dropdown checklist for each room.
while($rows = mysql_fetch_array($query)){
<!-- Apply dropdown check list to the selected items -->
<script type="text/javascript">
$(document).ready(function(){$("#<?php echo $bnum; ?>").dropdownchecklist( { width: 300 } );});
</script>
<!-- This is the JQuery Dropdown checklist !-->
<select id="<?php print $bnum;?>" multiple="multiple" name="dietdata[]" >
<option value="0"></option>
<?php
//query drop-down list
$sqlakh="select diet_id,diet_name from bmsdb.diettypes";
$resultakh=mysql_query($sqlakh);
while($rowsakh= mysql_fetch_array($resultakh)) { ?>
<option value='<?php echo $rowsakh['diet_id'].'|'.$bnum; ?>'><?php echo $rowsakh['diet_name']; ?>
</option>
<?php }
}//end while ?>
</select>`
When I submit this form in the server side, this is what I do to extract the data from the array of the dropdown checklist:
$data2 = $_POST['data2']; //total no of data
$dietdata= $_POST['dietdata']; //diet data
$roomlist= $_POST['data3']; //patient room number
for($k=0; $k<=sizeof($data3); $k++){
$dietarray= $dietdata[$k];
$separatediet= (explode('|',$dietarray));
$output_array[]=array("diet"=>$separatediet['0'],"room"=>$separatediet['1']);
for($j=0; $j<=sizeof($data3); $j++){
if($output_array[$k][room]== $roomlist[$j]){
$rekod[$output_array[$k][room]]= $output_array[$k][diet];
}
}
}print_r($rekod);
The print_r output when I submitting the form is like this:
Array ( [501] => 3 [502] => 4 [] => )
Then I extract the array using implode to separate the room and the diet type.
Array ( [0] => 2|501 [1] => 3|501
[2] => 3|502 [3] => 4|502 )
What I want is for the array to be like this. Is there any way for me to make the array to be like this, or a better structure to use?
Array ( [501] => 2,3) //2,3 is the diet type group together after being extracted from the array above
[502] => 3,4 )
Assuming you're keeping all the code up to the point where you're imploding to generate your final array:
Array ( [0] => 2|501 [1] => 3|501
[2] => 3|502 [3] => 4|502 )
You could create the array you're asking for like this:
$out = array(); // The final output array
foreach ($your_array as $item) {
$vals = explode('|', $item);
if (!isset($out[$item[1]])) $out[$item[1]] = array();
$out[$item[1]][] = $item[0];
}
foreach ($out as &$item) {
$item = implode(',', $item);
}
This is my final code. Which generata output like this
Array ( [501] => 2,3,4 [502] => 3,4 [503] => 5,6 )
Thanks to Hibiscus for your help.
$out = array(); // The final output array
foreach ($status as $item) {
$vals = explode('|', $item);
if (!isset($out[$vals[1]])) $out[$vals[1]] = array();
$out[$vals[1]][] = $item[0];
}
$item=array();
foreach ($out as &$item)
{
$item = implode(',', $item);
}
$diet = array();
$data3 = $_POST['data3'];
for($h=0; $h<=$data2; $h++)
{
$data3 = $_POST['data3']; //patient bnum
$data3 = $data3[$h];//bnum
if(!empty($out[$data3]))
{
$diet[$data3] = $out[$data3];
}
} print_r($diet);

Categories