I had no problem on getting the values from HTML form but my problem is how to combine all values that I got in one array?
Example:
Quantity[] is separated from CheckBox[]. If the checkbox has been checked, only all values of it (Pizza ID, Name, Price and Quantity) should be transfer into one array.
Snippet Code:
<tbody>
<?php
$Row = 0;
while ($Row = mysqli_fetch_array($Retrieval_Query, MYSQLI_ASSOC)){
$pizzaID = $Row['pizzaID'];
$pizzaName = $Row['pizzaName'];
$pizzaPrice = $Row['pizzaPrice'];
?>
<tr>
<td><?php echo $pizzaID; ?></td>
<td><?php echo $pizzaName; ?> </td>
<td><?php echo $pizzaPrice; ?> </td>
<td><input type = "number" name = "Quantities[]" placeholder = "0"/></td>
<td><input type = "checkbox" name = "CheckBox[]" value="<?=$pizzaID?>,<?=$pizzaName?>,<?=$pizzaPrice?>" placeholder = "0"/></td>
</tr>
<?php } ?>
</tbody>
</table>
</form>
<button type="submit" form="form1" value="Atc" name="atc" class="btn btn-warning">Add to Cart</button>
Back end:
<?php
$values = array();
$quantities = array();
if(isset($_POST['atc'])){
//Operation to retrieve all values from HTML CheckBox[] and Quantities[] since they are separated inputs
//And push all values that has been retrieved into same array
foreach($_POST['CheckBox'] as $key => $value){
array_push($values, $value);
}
foreach($_POST['Quantities'] as $key => $value){
array_push($values, $value);
}
Current Output:
Desired Output:
How to achieve the desired output? Is my technique on getting the values from HTML
(2 Separated arrays) is right? How to make all values to be combine in
just one array?
You'll get a better understanding of what is happening if you view the POSTed data as PHP sees it in your script. At the top of your PHP add:
print_r($_POST);
die();
And you'll see:
Array
(
[Quantities] => Array
(
[0] => 23
[1] =>
[2] => 33
)
[CheckBox] => Array
(
[0] => 1,Hawaiian,150
[1] => 3,Four Cheese,300
)
Next, array_push simply appends elements to the end of an array. So you're just joining those 2 arrays one after the other, without preserving the fact that the elements relate to each other.
The next problem is that checkboxes don't appear in the POSTed data at all if they are not checked. You can see that there are only 2 elements in the Checkbox array, even though you have 5 pizzas in the form. That means you can't connect elements from the Quantities array and the CheckBox array using the key. Key 1 in Quantities corresponds to Bacon and Cheese, but key 1 in CheckBox corresponds to Four Cheese.
I don't see an easy way to solve this using your current approach.
But take a step back - do you really want to POST the price to your handling code? What if I edit the form in my browser and set the price to "1", or "0"? You should never trust data coming from the browser, and you have this data in your database already.
Do you really care about a pizza in the order if the quantity is 0? You can get rid of the checkbox, since entering a number in the quantity field controls whether or not they're getting that pizza.
Here's an alternative approach:
<?php while ($Row = mysqli_fetch_array($Retrieval_Query, MYSQLI_ASSOC)) { ?>
<tr>
<td><?php echo $Row['pizzaID']; ?></td>
<td><?php echo $Row['pizzaName']; ?></td>
<td><?php echo $Row['pizzaPrice']; ?></td>
<td>
<!-- include the ids, we can refer to those for each quantity -->
<input type="hidden" name="ids[]" value="<?php echo $Row['pizzaID']; ?>"/>
<input type="number" name="Quantities[]" placeholder = "0"/>
</td>
</tr>
<?php } ?>
Now on your back end, you can do something like:
foreach ($_POST['Quantities'] as $key => $value) {
if (empty($value) || $value == 0) {
// wasn't ordered! Skip to the next.
continue;
}
$id = $_POST['ids'][$key];
// Now you know they want $value of pizza id $id. You can look
// up the price, name, etc, from your DB, same as you did to
// display them on the form in the first place.
}
Side note - it might just be copy-paste issues between your real code and your question here on SO, but the submit button should be inside the </form> tag.
You could use the "associative array" style of naming your form inputs, as described in the PHP docs:
http://www.php.net/manual/en/faq.html.php#faq.html.arrays
Use your unique pizzaID as the key for both input arrays:
(Include a string element (I've used id_ here) to ensure that it will be a string key that we will be working with later as the array functions work differently for numerically indexed arrays)
while ($Row = mysqli_fetch_array($Retrieval_Query, MYSQLI_ASSOC))
{?>
<input type = "number" name = "Quantities[id_<?=$pizzaID?>]" id="qty<?php echo $cnt?>" placeholder = "0"/>
<input type = "checkbox" name = "CheckBox[id_<?=$pizzaID?>]" data-cnt="<?php echo $cnt?>" value="<?=$pizzaID?>,<?=$pizzaName?>,<?=$pizzaPrice?>" placeholder = "0"/>
<?php }
When you read the POST values in, each named array will be in the format of key => [id => value].
You can then use the id key strings to unify the values in the 2 arrays using array_merge_recursive.
$q = $_POST['Quantities'] ?? [];
$c = $_POST['CheckBox'] ?? [];
$merged = array_merge_recursive($q, $c);
This will combine all of the values associated with each pizzaId key. The resulting array looks like this:
Array
(
[id_1] => Array
(
[0] => 1,Hawaiian,150
[1] => 23
)
[id_3] => Array
(
[0] => 3,Four Cheese,300
[1] => 33
)
)
Now you can squash these merged arrays to produce a single comma delimited list for each pizzaId:
$squashed = array_map(function($v){
return is_array($v)
? implode(',', $v)
: $v;
}, $merged);
The $squashed array will now contain:
Array
(
[id_1] => 1,Hawaiian,150,23
[id_3] => 3,Four Cheese,300,33
)
The id_ prefix can then be stripped out of the keys if required.
One caveat would be that if the user has only submitted values for one of the 2 input fields, then the resulting array will only contain that single value and it would take further analysis to determine whether this was the Quantity or Checkbox value (e.g. checking against is_int() could determine whether the value belonged to Quantity).
$values = array();
$quantities = array();
foreach($_POST['CheckBox'] as $key => $value){
array_push($values, $value);
}
$quantities = $_POST['Quantities'];
$i=0;
foreach ($quantities as $q){
if($q){
$values[$i] = $values[$i].','.$q;
$i++;
}
}
below is my output
Array
(
[0] => 1,Hawa,150,23
[1] => 3,Four,300,33
)
Here your check box array indexing is different from quantity indexing so bcz of that you have to change the way of code:
on click check box you have to con-cat quantity with check box value like:
$(document).on('click','input[name=checkBoxName]',function()
{
if($(this).is(":checked")) //check if checkbox checked
{
var key = $(this).attr('data-cnt');
var qty = $("#qty"+key).val(); //return qty id value like qty1
$(this).val($(this).val()+','+qty);
}
else //check box not checked then remove last qty value
{
var text = $(this).val();
var resArray = text.split(",");
var poppedItem = resArray.pop();
var result = resArray.toString();
$(this).val(result);
}
});
before while loop declare cnt=0;
while()
{?>
<input type = "number" name = "Quantities[]" id="qty<?php echo $cnt?>" placeholder = "0"/>
<input type = "checkbox" name = "CheckBox[]" data-cnt="<?php echo $cnt?>" value="<?=$pizzaID?>,<?=$pizzaName?>,<?=$pizzaPrice?>" placeholder = "0"/>
<?php }
when you post data then you will get :
foreach($_POST['CheckBox'] as $key => $value){
array_push($values, $value);
}
var_dump($values);
you will get expected output.
I know this has been posted a million times over but I cant find an example where the same item was being called for the same use but with different values. I am using lightbox and I need my <a> to pull in the size=full and my <img> to pull in the size=thumbnail. I am successfully doing this but my nested foreach statements are casing duplicates.
<?php
$dyno_images = rwmb_meta( 'gallery-images', 'type=image_advanced&size=thumbnail' );
$dyno_images_lrg = rwmb_meta( 'gallery-images', 'type=plupload_image&size=full' );
?>
<?php
foreach ( $dyno_images_lrg as $dyno_image_lrg ) {
foreach ( $dyno_images as $dyno_image ) {
echo '<figure class="gallery-item"><div class="gallery-icon landscape"><img src="'.$dyno_image['url'].'" aria-describedby="gallery-1-584" class="attachment-full"></div></figure>';
}
}
?>
I assume that each item in $dyno_images_lrg corresponds to an item in $dyno_images.
In that case you only want to loop once and pick out the corresponding item:
foreach ( $dyno_images_lrg as $key => $dyno_image_lrg ) {
$dyno_image = $dyno_images[$key];
//Snipped for brevity - rest of the code should remain the same
}
<input name="auth[]" type="text" id=" " value="<?php echo $cite_aut[$i]; ?>">
Above are text fields in html. Now how to get text fields values in a array variable in another php page.
I tried it by using foreach loop (foreach($val as $_POST['author'])... but it fetch 1 extra value for $val, if there are 5 text boxes then it is fetching 6 values, 6th value is "array".
can someone explain how to do it?
Should be:
foreach($_POST['auth'] as $key => $val) {
......
}
TRY
foreach($_POST['auth'] as $key => $val) {
echo $val;
}
I had to make some changes to my app to work with a relationship change in my db.
Originally I had whats below for a 1::0-1 relationship
if ($model->address->AddressLine1) echo $model->address->AddressLine1.'<br />';
if ($model->address->AddressLine2) echo $model->address->AddressLine2.'<br />';
if ($model->address->city->Name) echo $model->address->city->Name;
if ($model->address->city->regionCode->RegionCode) echo ', '.$model->address->city->regionCode->RegionCode;
but had to change it to work with a 1::0-n relationship
foreach ($model->address as $al1)
foreach ($model->address as $al2)
foreach ($model->address as $al2)
foreach ($model->address as $city)
foreach ($model->address as $region) {
echo $al1->AddressLine1.' '.$al2->AddressLine2.'<br/>'.$city->city->Name.' '.$city->city->regionCode->RegionCode;
}
I want to retain the functionality of the if in my original code. With the original code I was able to use
', '.
in
if ($model->address->city->regionCode->RegionCode) echo
', '. $model->address->city->regionCode->RegionCode;
to only add a comma after City only when a Region is present in the db.
So how can I get that back and utilize if within my array?
You only need one foreach loop — you're just iterating through a single array.
You can stick the conditionals into the foreach loop, updating the variable name. This assumes that $model->address is an array. On each iteration $address will be set to a subsequent element of that array.
foreach ( $model->address as $address ) {
if ($address->AddressLine1) echo $address->AddressLine1.'<br />';
if ($address->AddressLine2) echo $address->AddressLine2.'<br />';
if ($address->city->Name) echo $address->city->Name;
if ($address->city->regionCode->RegionCode) echo ', '.$address->city->regionCode->RegionCode;
}
For more information:
PHP foreach documentation
foreach tutorial
I am working with SimplePie and I cannot figure out how to output the count, or the key values for the loop.
Shouldn't this
<?php foreach ($feed->get_items() as $item): ?>
<?php
$i = key($item);
echo $i;
?>
<?php endforeach; ?>
, or this
<?php foreach ($feed->get_items() as $item): ?>
<?php
$i = count($item);
echo $i;
?>
<?php endforeach; ?>
be outputting a unique number for each?
uniqid() Doesn't work in this case, because I am running the loop twice on the page and trying to match up one list of elements with another based on ID.
A single argument used with as is interpreted as a variable in which to store the value, not the key. If you want the key, you need to use => in a manner like the following:
foreach ($feed->get_items() as $key => $item):
echo $key;
endforeach
As a sidenote, you're using key() and count() on an item in the array, rather than the array as a whole, which is invalid. As far as I'm aware, there's no guarantee that key() will work as you expect even if applied to the whole array. It's meant for loops where you control the iteration, as with next.
To get the 'count' in a foreach you would need an extra variable. Getting the key is easy and the same if the array is indexed in order instead of associative. Here is an example including both:
$array = array(
'foo' => 'bar'
);
$i = 0;
foreach ($array as $key => $value)
{
/*
code where $i is the 'count' (index) and $key is the associative $key.
*/
/* $i == 0 */
/* $key == 'foo' */
/* $value == 'bar' */
$i++;
}
key($item) that you're using above doesn't work because you're trying to get the key of a value that no longer is associated with the original array.
count($item) is the count of a subarray $item.
you can use get_id() method
like :
foreach ($feed->get_items() as $item)
{
$prev_ids = array('guid1', 'guid2', 'guid3', 'guid4');
if (in_array($item->get_id(true), $prev_ids))
{
echo "This item is already stored.";
}
else
{
echo "This is a new item!";
}
}