I received help already with a previous question about posting an array.
Now I'm trying to add more arrays to the loop
Here's the html
<input class="input stickyinput" type="number" name="pestcount[]">
<input type="hidden" name="cardtype[]" value="<?= htmlspecialchars($obj['cardtype']) ?>" />
<input type="hidden" name="cardid[]" value="<?= htmlspecialchars($obj['card_id']) ?>" />
<input type="hidden" name="pestname[]" value="<?= htmlspecialchars($pestname['scoutlogpestname']) ?>" />
Here's the php
for ($i=0; $i < count($_POST['cardid']); $i++ ) {
$card_id = $_POST['cardid'][$i];
$card_type = $_POST['cardtype'][$i];
$pest_count = $_POST['pestcount'][$i];
$pest_name = $_POST['pestname'][$i];
$sql ="INSERT INTO scout_logpestnum (pest_name,pest_count,card_id,card_type)
VALUES (:pest_name,:pest_count,:card_id,:card_type)";
$q = $pdo->prepare($sql);
$q->execute(array(':pest_name'=>$pest_name,':pest_count'=>$pest_count,':card_id'=>$card_id,':card_type'=>$card_type));
}
So what is the proper format for adding addition arrays from the form?. Thanks;)
Here's what my array looks like.
Array (
[pestcount] => Array (
[0] => 1
[1] => 2
[2] => 3
)
[cardtype] => Array (
[yellcard] =>
)
[cardid] => Array (
[1] =>
)
[pestname] => Array (
[Aphids] =>
[Thrips] =>
[White-Fly] =>
)
Assuming that pests and cards are separate collections, you can simply use a prefix to identify them in $_POST data. For example...
<input name="pests[<?= htmlspecialchars($pestname['scoutlogpestname']) ?>][<?= $obj['card_id'] ?>]" ...
and
<input name="cards[<?= htmlspecialchars($obj['cardtype']) ?>][<?= $obj['card_id'] ?>]" ...
This would produce HTML like
<input name="pests[Aphids][1]" ...
<input name="cards[yellcard][1]" ...
Then, in your form handler...
$pests = $_POST['pests'];
foreach ($pests as $pest_name => $values) {
foreach ($values as $card_id => $pest_count) {
echo $pest_name, $card_id, $pest_count;
}
}
$cards = $_POST['cards'];
foreach ($cards as $card_type => $values) {
foreach ($values as $card_id => $value) {
echo $card_type, $card_id, $value;
}
}
Related
despite my efforts I wasn't able to find a suitable solution. Here is the problem:
All the data comes from a form with text fields named name[], gender[], and age[].
print_r($_POST) looks like:
[name] => Array ([2] => Adam [6] => Suzy )
[gender] => Array ( [2] => male [6] => female )
[age] => Array ( [2] => 30 [6] => 25 )
I am trying to iterate it like this:
foreach ($array as $value)
{
echo $value['name'].$value['gender'].$value['age']."<br>";
}
The result should look like this:
Adam - male - 30
Suzy - female - 25
You are close - but the syntax for creating arrays is slightly different.
$array = array (
array('name' => 'Adam', 'gender' => 'male', 'age' => 30),
array('name' => 'Suzy', 'gender' => 'female', 'age' => 25),
);
foreach ($array as $value)
{
echo $value['name'].$value['gender'].$value['age']."<br>";
}
You've got two options - you could create an array of two items; each has three details about a single person. That's what I did and it suits the loop you've shown.
Or you can have three parallel arrays - one with two names, one with two genders and one with two ages.
That second way would look more like:
$array = array(
'name' => array('Adam','Suzy'),
'gender' => array('male','female'),
'age' => array(30,25)
);
But it would be harder to get the output you want from that.
$array2 = array(
'name' => array('Adam','Suzy'),
'gender' => array('male','female'),
'age' => array(30,25)
);
for($i=0;$i<count($array2['name']);$i++){
echo $array2['name'][$i].$array2['gender'][$i].$array2['age'][$i].'<br/>';
}
Each of the arrays in $_POST have the same set of keys:
$_POST = array(
'name' => array(2 => 'Adam', 6 => 'Suzy'),
'gender' => array(2 => 'male', 6 => 'female'),
'age' => array(2 => '30', 6 => '25')
)
You can iterate one of the inner arrays, and use its key to access the corresponding values in the other arrays.
foreach ($_POST['name'] as $key => $name) {
echo $name . $_POST['gender'][$key] . $_POST['age'][$key] . "<br>";
}
foreach ($array as $id=>$value)
{
echo $value . $gender[$id] . $age[$id] . "<br>";
}
First of all I've modified the array structure that you posted on your question because it is not valid for in php. Then If I don't misunderstood you requirements then you've this array structure and you want to archive this-
<?php
$array = array (
'name'=>array('Adam', 'Suzy'),
'gender'=>array('male', 'female'),
'age'=>array(30, 25)
);
$i=0;
foreach ($array as $key=>$value)
{
if($i==2)break;
echo $array['name'][$i]."-".$array['gender'][$i] ."-". $array['age'][$i] ."<br>";
$i++;
}
?>
OR
<?php
$array = array (
'name'=>array('Adam', 'Suzy'),
'gender'=>array('male', 'female'),
'age'=>array(30, 25)
);
foreach ($array['name'] as $index=>$name)
{
echo $name."-".$array['gender'][$index] ."-". $array['age'][$index] ."\n";
}
?>
Program Output:
Adam-male-30
Suzy-female-25
DEMO: https://eval.in/1039966
#Being Sunny
Veeeery close to that sir I'v used back in 2003. Here is the working solution:
<?
echo "<pre>";
print_r($_POST);
echo "</pre>";
foreach ($_POST['name'] as $key => $name) {
echo "NAME=".$_POST['name'][$key]."gender=" . $_POST['gender'][$key] . "AGE=".$_POST['age'][$key] . "<br>";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>
</head>
<body>
WOKSING SOLUTION:
<code>echo "<pre>";
print_r($_POST);
echo "</pre>";
foreach ($_POST['name'] as $key => $name) {
echo "NAME=".$_POST['nemae'][$key]."gender=" . $_POST['gender'][$key] . "AGE=".$_POST['age'][$key] . "<br>";
}
</code>
<form method="post">
<input type="text" name="name[]" />
<input type="text" name="gender[]"/>
<input type="text" name="age[]"/>
<br />
<input type="text" name="name[]" />
<input type="text" name="gender[]"/>
<input type="text" name="age[]"/>
<input type="submit" />
</form>
</body>
</html>
I'm trying to post and receive a two dimensional array, but I can't get it to work.
Could you guys help me out?
Thanks in advance!
Here is my code:
$items[] = array(
'pid' => $pid
, 'qty' => $product_qty
);
<input type="hidden" name="items[]" id="pid" />
foreach ($_POST['items'] as $row) {
$pid = $row['pid'];
$product_qty = $row['qty'];
}
Change your code in a way like this:
$items = array('pid' => $pid, 'qty' => $product_qty);
foreach( $items as $key => $val )
{
echo '<input type="hidden" name="items['.$key.']" value="'.$val.'" id="'.$key.'" />';
}
In your original code, $items[] add a new item to array $items.
Also, HTML doesn't interpret php variables, so your <input name="items[]" will produce $_POST[items][0] with an empty value.
It's as simple as this:
$myarr = array( 'pid' => array($pid), 'qty' => array($product_qty));
I am having a $_POST array look like this:
Array
(
[veryfy_doc_type] => Array
(
[0] => 1
[1] => 2
)
[id_number] => Array
(
[0] => 3242424
[1] => 4456889
)
[document_issuer] => Array
(
[0] => 1
[1] => 3
)
[verify_doc_expiry_date] => Array
(
[0] => 2016-01-26
[1] => 2015-02-20
)
[doc_id] => Array
(
[0] => 15
[1] => 16
)
[user_id] => Array
(
[0] => 14
[1] => 14
)
)
Using this array I need to get each values into php variables.
I tried it something like this, but it doesn't work for me.
foreach($_POST AS $k => $v) {
//print_r($v);
list($doc_type, $id_number, $issuer, $expiry_date, $doc_id, $user_id) = $v;
}
echo "Type = $doc_type";
Can anybody tell me how to figure this out.
Thank you.
This might help you since you can also use extract in php to create variables.
<?php
$_POST = array(
'veryfy_doc_type'=> array(1,2),
'id_number' => array(3242424,4456889),
'document_issuer'=> array(1,3),
'verify_doc_expiry_date'=> array('2016-01-26','2015-02-20'),
'doc_id' => array(15,16),
'doc_id' => array(14,14)
);
extract($_POST);
print_r($veryfy_doc_type);
print_r($id_number);
So you want to reference each of the sub-array values while looping the main array... maybe something like this?
// Loop one of the sub arrays - you need to know how many times to loop!
foreach ($_POST['veryfy_doc_type'] as $key => $value) {
// Filter the main array and use the $key (0 or 1) for the callback
$rowValues = array_map(function($row) use ($key) {
// Return the sub-array value using the $key (0 or 1) for this level
return $row[$key];
}, $_POST);
print_r($rowValues);
}
Example: https://eval.in/498895
This would get you structured arrays for each set of data.
From here I'd suggest you leave the arrays as they are rather than exporting to variables, but if you wanted to you you could use the list() as in your example.
You can use a MultipleIterator for that:
<?php
$post = array(
'veryfy_doc_type' => array('1','2'),
'id_number' => array('3242424','4456889'),
'document_issuer' => array(1,3),
'verify_doc_expiry_date' => array('2016-01-26','2015-02-20'),
'doc_id' => array(15,16),
'user_id' => array(14,14)
);
$mit = new MultipleIterator(MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_ASSOC);
foreach($post as $k=>$v) {
$mit->attachIterator( new ArrayIterator($v), $k);
}
foreach( $mit as $row ) {
echo $row['doc_id'], ' ', $row['id_number'], ' ', $row['verify_doc_expiry_date'], "\r\n";
}
prints
15 3242424 2016-01-26
16 4456889 2015-02-20
If you have control over the client code you can change the names of the POST parameters in a way that php build this structure automagically. E.g.
<form method="POST" action="test.php">
<input type="hidden" name="record[0][veryfy_doc_type]" value="1" />
<input type="hidden" name="record[0][id_number]" value="3242424" />
<input type="hidden" name="record[0][document_issuer]" value="1" />
<input type="hidden" name="record[0][verify_doc_expiry_date]" value="2016-01-26" />
<input type="hidden" name="record[0][doc_id]" value="15" />
<input type="hidden" name="record[0][user_id]" value="14" />
<input type="hidden" name="record[1][veryfy_doc_type]" value="2" />
<input type="hidden" name="record[1][id_number]" value="4456889" />
<input type="hidden" name="record[1][document_issuer]" value="3" />
<input type="hidden" name="record[1][verify_doc_expiry_date]" value="2015-02-20" />
<input type="hidden" name="record[1][doc_id]" value="16" />
<input type="hidden" name="record[1][user_id]" value="14" />
<input type="submit" />
</form>
would do/cause that.
If you only want to get the value of the post then you can have a simple multidimentional loop. no need to make it broad
foreach($_POST as $keyName => $row){
// $keyName will be verify_doc_type, id_number, etc..
foreach($row as $value){
// do something
echo $value;
}
}
Hope that helps.
This method will generate variables of same name as in POST array:
foreach ($_POST as $k => $v )
{
$$k = addslashes(trim($v ));
}
I know this post is a bit old, but I was recently trying to achieve this very same thing.
Hopefully the answer will point others in the right direction.
As per the documentation on list():
Since PHP 7.1, keys can be specified
Example from the manual:
<?php
$arr = ['locality' => 'Tunis', 'postal_code' => '1110'];
list('postal_code' => $zipCode, 'locality' => $locality) = $arr;
echo $zipCode; // will output 1110
echo $locality; // will output Tunis
?>
https://www.php.net/manual/en/function.list.php#121094
I am trying to create a php array from posted values and then json_encode to achieve this:
[{"network_type":"facebook","network_url":"fb.com/name"},{"network_type":"twitter","network_url":"#name"},{"network_type":"instagram","network_url":"#name"}]
which after json_decode looks like:
array(
[0] => stdClass(
network_type = 'facebook'
network_url = 'fb.com/name'
)
[1] => stdClass(
network_type = 'twitter'
network_url = '#name'
)
[2] => stdClass(
network_type = 'instagram'
network_url = '#name'
)
)
My php looks like this:
$social_data = array(
'network_type' => $this->input->post('network_type'),
'network_url' => $this->input->post('network_url')
);
and so the array is not grouped the way I want it, but rather by the field name:
array(
['network_type'] => array(
[0] => 'facebook'
[1] => 'twitter'
[2] => 'instagram'
)
['network_url'] => array(
[0] => 'fb.com/name'
[1] => '#name'
[2] => '#name'
)
and therefore the result of the json_encode isn't grouped how I want it:
{"network_type":["facebook","twitter","instagram"],"network_url":["fb.com/name","#name","#name"]}
)
So the question is...how do I adjust my php so the array is correct?
--- here's the input fields:
<?php
foreach ($social as $key => $value) {?>
<p>
<label for="network_type"><input type="text" size="20" name="network_type[]" value="<?php echo $value -> network_type; ?>" placeholder="Social Network" /></label>
<label for="network_url"><input type="text" size="20" name="network_url[]" value="<?php echo $value -> network_url; ?>" placeholder="URL or Handle" /></label>
<a class="remNetwork" href="#">Remove</a>
</p>
<?php } ?>
----latest update: this is sooooo close!-----
Ok, for some reason (probably me botching things one way or another), both suggested methods below didn't quite get me there....but, a mix of both methods has gotten me close:
This if/loop/array setup:
$network_type = (array)$this->input->post('network_type', true);
$network_url = (array)$this->input->post('network_url', true);
$social_data = array();
if (($counter = count($network_type)) == count($network_url)){
for($i = 0;$i < $counter; $i++) {
$social_data[$i] = array(
'network_type' => $this->input->post('network_type[$i]'),
'network_url' => $this->input->post('network_url[$i]'),
);
}
}
paired with this input loop:
<?php
foreach ($social as $key => $value) {
?>
<p>
<label for="network_type"><input type="text" size="20" name="network_type[]" value="<?php echo $value -> network_type; ?>" placeholder="Social Network" /></label>
<label for="network_url"><input type="text" size="20" name="network_url[]" value="<?php echo $value -> network_url; ?>" placeholder="URL or Handle" /></label>
<a class="remNetwork" href="#">Remove</a>
</p>
<?php } ?>
is yielding the following:
array(
[0] => array(
['network_type'] => FALSE
['network_url'] => FALSE
)
[1] => array(
['network_type'] => FALSE
['network_url'] => FALSE
)
[2] => array(
['network_type'] => FALSE
['network_url'] => FALSE
)
)
So, I think if I can figure out why these values are false, then we've done it!
Thanks and appreciation for your patience and help in advance...
-- update again ----
To my dismay, I've left out a piece that's perhaps critical...the coffee script that's dynamically creating the form fields when there's more than one social:
$ ->
socialDiv = $("#social")
i = $("#social p").size() + 1
index = 0
$("#addNetwork").click ->
$("<p><label for=\"network_type[]\"><input type=\"text\" id=\"network_type[]\" size=\"20\" name=\"network_type[]\" value=\"\" placeholder=\"Social Network\" /></label><label for=\"network_url[]\"><input type=\"text\" id=\"network_url[]\" size=\"20\" name=\"network_url[]\" value=\"\" placeholder=\"URL or Handle\" /></label> Remove</p>").appendTo socialDiv
i++
false
$(document).on "click", ".remNetwork", ->
#$(".remNetwork").bind "click", ->
if i > 1
$(this).parent("p").remove()
i--
false
In your example, i can asume that network_type and network_url are inputs like:
<input type="text" name="network_type[]" /> and <input type="text" name="network_url[]" />
so in order to accomplish what you want you would:
<?php
$networkType = (array)$this->input->post('network_type', true);
$networkUrl = (array)$this->input->post('network_url', true);
$networkData = array();
if (($counter = count($networkType)) == count($networkUrl)) {
for ($i = 0; $i < $counter; ++$i) {
$networkData[] = array(
'network_type' => $networkType[$i],
'network_url' => $networkUrl[$i]
);
}
}
?>
and should give you the desired json.
However, this approach is a bit clunky and unreliable.
Instead, i would define the input fields like:
<input type="text" name="network[0][network_type]" /> and <input type="text" name="network[0][network_url]" />
<input type="text" name="network[1][network_type]" /> and <input type="text" name="network[1][network_url]" />
and i would generate the php array like:
<?php
$networkData = (array)$this->input->post('network', true);
?>
Just my two cents :)
L.E:
To make it detailed and create the std objects from your array, you would:
$networkData = array();
if (($counter = count($networkType)) == count($networkUrl)) {
for ($i = 0; $i < $counter; ++$i) {
$obj = new StdClass();
$obj->network_type = $networkType[$i];
$obj->network_url = $networkUrl[$i];
$networkData[] = $obj;
}
}
print_r($networkData);
You can use a for loop to iterate through as you feed them into the $social_data array. It would be
for($i = 0;$i < $items.length;$i++) {
$social_data[$i] = array(
'network_type' => $this->input->post('network_type[$i]'),
'network_url' => $this->input->post('network_url[$i]'),
);
The resulting array will look like:
$social_data[0] ->
'network_type' => 'facebook',
'network_url' => 'fbook.com/user'
$social_data[1] ->
...etc
I'm not totally sure what context you're getting the network_type and url but they will both be arrays and looping through for each individual value is what to do. Without the rest of the code it's hard to get much more specific but hopefully this will point you in the right direction.
I have multiple items with name module_name, and each of them have multiple input fields. Please see below:
<input type="hidden" value="slideshow" name="module_name[]">
<input type="hidden" value="" name="slide_title[]">
<input type="hidden" value="" name="slide_info[]">
<input type="hidden" value="" name="slide_title[]">
<input type="hidden" value="" name="slide_info[]">
I want to get all data when it is posted, so I'm trying this:
if(isset($_POST['module_name'])){
foreach ($_POST['module_name'] as $k => $v) {
foreach ($_POST['slide_title'] as $key => $value) {
$slide_title = addslashes($_POST['slide_title'][$key]);
$slide_info = addslashes($_POST['slide_info'][$key]);
$arr[] = array(
'slide_title' => $slide_title,
'slide_info' => $slide_info,
);
}
}
print_r($arr); //incorrect data
}
I want to get data of each module_name in an array, but with the above code I do not get correct data in the array, it displays the repeating data.
If you have more than one slide_title and slide_info for one module_name i think you have to change your structure:
<input type="hidden" value="slideshow" name="module_name[1]">
<input type="hidden" value="" name="slide_title[1][]">
<input type="hidden" value="" name="slide_info[1][]">
<input type="hidden" value="" name="slide_title[1][]">
<input type="hidden" value="" name="slide_info[1][]">
...
<input type="hidden" value="slideshow" name="module_name[2]">
<input type="hidden" value="" name="slide_title[2][]">
<input type="hidden" value="" name="slide_info[2][]">
<input type="hidden" value="" name="slide_title[2][]">
<input type="hidden" value="" name="slide_info[2][]">
So with this structure you can loop through your data like this:
$arr = array();
foreach($_POST['module_name'] as $key => $value) {
$data = array();
foreach($i = 0; $i < count($_POST['slide_title'][$key]); $i++) {
$data[] = array(
"slide_title" => $_POST['slide_title'][$key][$i],
"slide_info" => $_POST['slide_info'][$key][$i]
);
}
$arr[$value] = $data;
}
An result would look like this:
"module_name_1" => array(
array("slide_title" => "slide_title_1", "slide_info" => $slide_info_1),
array("slide_title" => "slide_title_2", "slide_info" => $slide_info_2),
array("slide_title" => "slide_title_3", "slide_info" => $slide_info_3)
),
"module_name_2" => array(
array("slide_title" => "slide_title_1", "slide_info" => $slide_info_1),
array("slide_title" => "slide_title_2", "slide_info" => $slide_info_2),
array("slide_title" => "slide_title_3", "slide_info" => $slide_info_3)
)
...
You should notice, that this loop expect the same amount of slide_title and slide_info fields for each module_name.
I hope this is the desired result.