Array multi-dimensional error PHP - 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'] ;
}

Related

Array session showing different values on different pages PHP

For context, I'm relevantly new to PHP and am trying to develop a simple quiz application but came across a roadblock which I just can't seem to find any solutions to for many hours. In short, I'm using a session to store an array of question ID's and answers for reference on another page, but when I print the array on the other page, the values of both sessions are completely different and I'm not sure what I'm doing wrong.
Additionally, the correct answers are always wrong and seem to check with the different session. Below are the relevant snippet of codes, session_start() is included in both.
quiz.php
<form method="post" action = "">
<div class="align-items-center justify-content-center">
<?php
$data = getQuestion($link,$_SESSION['typeSelected'],$_SESSION["questionCount"]); // sql query function
$i = 1;
$answers = array();
$ids = array();
while($row = mysqli_fetch_array($data)) {
$answers[] = (int) $row['answer'];
$ids[] = (int) $row['id'];
echo $answers[$i-1] . "<br>" . $ids[$i-1] . "<br>"; // shows correct answer row and question ID from database for my reference
echo " <div class = \"question-div\">
<h3><label>" . $i . ". " . $row['info'] . "</label></h3>
</div>
<div>
<h4><label class=\"form-check-label\">
<input name=\"answer$i\" class=\"form-check-input\" type=\"radio\" value=1 > ".$row['one'].
"</label></h4>
</div>
<div>
<h4><label class=\"form-check-label\">
<input name=\"answer$i\" class=\"form-check-input\" type=\"radio\" value=2> ".$row['two']."
</label></h4>
</div>
<div>
<h4><label class=\"form-check-label\">
<input name=\"answer$i\" class=\"form-check-input\" type=\"radio\" value=3> ".$row['three']."
</label></h4>
</div>
<div>
<h4><label class=\"form-check-label\">
<input name=\"answer$i\" class=\"form-check-input\" type=\"radio\" value=4> ".$row['four']."
</label></h4>
</div>";
$i++;
}
?>
</div>
<input name="submit" type="submit" class="btn-primary" value="Submit">
</form>
<?php
$_SESSION["ids1"] = $ids; // creates a new session from array of questions asked
$_SESSION["answer1"] = $answers; // creates a new session with the array of correct answers
print_r($_SESSION["ids1"]); // eg: prints Array ( [0] => 32 [1] => 18 [2] => 24 [3] => 25 [4] => 19 )
echo "<br>";
print_r($_SESSION["answer1"]); // eg: prints Array ( [0] => 4 [1] => 2 [2] => 4 [3] => 3 [4] => 3 )
$point = 0;
$wrongs = array();
if(isset($_POST["submit"])) {
for($a=1; $a < $i; $a++) {
if(isset($_POST["answer$a"]) && ($_POST["answer$a"] == $_SESSION["answer1"][$a-1])) { // always incorrect and seems to check with the different session array shown on result.php
$point++;
}
else {
$wrongs[] = $ids[$a-1];
}
}
$_SESSION["test"] = $_POST["answer1"]; // for me to check value of option selected
$_SESSION["point"] = $point;
$_SESSION["wrongs"] = $wrongs;
setPoint($link,$_SESSION["email"],$point);
echo "<script>window.location.href='result.php';</script>";
}
?>
result.php
print_r($_SESSION['ids1']); // eg: prints Array ( [0] => 18 [1] => 23 [2] => 33 [3] => 19 [4] => 32 )
echo "<br>";
print_r($_SESSION['answer1']); // eg: prints Array ( [0] => 2 [1] => 1 [2] => 1 [3] => 3 [4] => 4 )
// arrays printed on each website have correct question and answer pairs, but I still don't understand why the sessions are different
Sorry if this was a little lengthy, it's my first time posting here and I'm at my wits end, having tried everything I could think of but can't see the solution. Any help would be greatly appreciated!

Add values and keys to session and store each individual addition (php)

I am at my wits end for last three days.
What i want to do is to code shopping-cart like functionality. So, i have two inputs that i want EACH to store in its own array.
something along the lines of:
<?php
session_start();
$input1 = [];
$input2 = [];
if(isset($_POST['submit']))
{
$input1 = $_POST['first'];
$input2 = $_POST['second'];
$_SESSION['test'] = [
'first' => array_push($input1),
'second' => array_push($input2)
];
}
var_dump($_SESSION['test']);
?>
and my html is as follows :
<form method="post">
<input type="text" name="first" value="">
<input type="text" name="second" value="">
<input type="submit" name="submit" value="array">
</form>
Now i expect the output of var_dump to be as follows:
Array(
[First] => ('Random1','Random2')
[Second] => ('Flower1','Flower2')
)
But what i get in the best case is:
Array(
[First] => Random1
[Second] => Flower1
[0] => Random2
[1] => Flower2
)
So, my question is 1) How can i add values to $_SESSION['test'] as an array
and 2) How can i store each input in it's corresponding array?
array_push takes at least two parameters: an array, and something to push into it. You're giving it the one input, and then are not pushing anything into it. Further, you're replacing your entire $_SESSION['test'] on every run, overwriting it with new (nonsense) values.
What you want is:
$_SESSION['test']['first'][] = $input1;
$_SESSION['test']['second'][] = $input2;
Append something to the end of the existing arrays, not overwrite them.

Send associative array from a multiple select

I need to send an associative array from a multiple select.
I have this code:
<select name="frontend_footer_menu_pages[]" id="frontend_footer_menu_pages" class="form-control" multiple>
<?php foreach($pages as $page): ?>
<option value="<?php echo $page->url; ?>">
<?php echo $page->page; ?>
</option>
<?php endforeach; ?>
And this is producing:
Array(
[0] => first/page,
[1] => second/page
)
I need to obtain something like this:
Array(
['first/page'] => 'First Page',
['second/page'] => 'Second Page']
);
I am not able to produce name/value in associative way and not in numeric way because I can't retrieve the content of option ($page->page)
Thank you in advance
G
When the form is submitted you will indeed get something like this array in PHP:
Array(
[0] => first/page,
[1] => second/page
)
This is how it works, and I would not suggest to try to change this behaviour. However, you can convert this to the associative array of your liking.
First create an associative array for your pages, so you can quickly find the page name for a given url:
// Create hash for the pages, keyed by their page name:
foreach ($pages as $page) {
$pageHash[$page->page] = $page->url;
}
You already have your submitted list of selected items. Your existing code will have something like this:
$selected = $_POST['frontend_footer_menu_pages'];
Now, to convert this to the associative array you are looking for, just use array_intersect with the hash we created above, and then swap keys and values with array_flip:
$selected = array_flip(array_intersect($pageHash, $selected));
The outcome will be something like this:
Array
(
[first/page] => First Page
[second/page] => Second Page
)

2D array PHP variables in between words

As the title says. I'm trying to store every value from $_POST['spell'.$j.'icon'.$i] inside a 2d array and I'm curious if there is any way to make this array look the same way so $spell[$j]icon[$i]
$spellicon=array();
for($i=1;$i<=$_POST['champ_number']; $i++){
for($j=1; $j<=$noofspellschamp[$i]; $j++){
$spellicon[$j][$i]=$_POST['spell'.$j.'icon'.$i];
}
}
EDIT Bit of code from the previous site. Data is nested so I need it to be in 2d array.
for($i=1;$i<=$champ_number; $i++){
echo $_POST['champno'.$i].'<br/>';
//echo '<input type="hidden" value="'.$_POST['champno'.$i].'" name="champno'.$i.'">';
$champno[$i] = $_POST['champno'.$i];
//echo '<input type="hidden" value="'.$_POST['noofspellschamp'.$i].'" name="noofspellschamp'.$i.'">';
$noofspellschamp[$i] = $_POST['noofspellschamp'.$i];
for($j=1; $j<=$_POST['noofspellschamp'.$i]; $j++){
echo '<select name="spell'.$j.'icon'.$i.'">';
echo '<option value="Passive">Passive</option>';
echo '<option value="Q" selected>Q</option>';
echo '<option value="W">W</option>';
echo '<option value="E">E</option>';
echo '<option value="R">R</option>';
echo '</select>';
if($i==1&&$j==1){
echo '<input type="text" name="spell'.$j.'title'.$i.'" placeholder="Spell '.$j.' name" required autofocus><br/>';
}
else{
echo '<input type="text" name="spell'.$j.'title'.$i.'" placeholder="Spell '.$j.' name" required><br/>';
}
Edit 2 Print_R($_POST)
Array (
[formid] => 6
[champ_number] => 2
[spell1icon1] => Q
[spell1title1] => spell1
[champno1spellno1] => 1
[description111] => sakdop
[change111] => buff
[spell1icon2] => Q
[spell1title2] => sdkop
[champno2spellno1] => 1
[description121] => sadas
[change121] => buff
[noofspellschamp] => {"1":"1","2":"1"}
[champno] => {"1":"Garen","2":"Katarina"}
[patch] => 0.03
)
There's no such thing as $spell[$j]icon[$i] in PHP. The approach you're using($spellicon[$j][$i]) is the only one in standard PHP (I mean, without classes).
But it'll be better if you do it like this: $spellicon[$i][$j], because it's the champion that has the spells, and not the other way around.
Code below is simplification. Check included topic. Just use
$_POST['spellicon'][$j][$i]
or
$_POST['spell'][$j]['icon'][$i]
and the you will have same naming convention as your variable.
Considering form building it will be cleaner and you can group your data with good manner. If you don't know how to send multidimensional arrays via POST, check this topic

PHP foreach loop through multidimensional array

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.

Categories