post two dimensional array in php - php

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));

Related

Passing an Array Key to a variable

I have a script which puts products into a shopping cart;
if (isset($_POST["top"])) {
$name = $_POST["name"];
$_SESSION[$$name] += 1;
$$name = $_SESSION[$$name];
$name = $name.$$name;
$piid = $_SESSION["piid"];
$prod = $_POST["prod"];
$_SESSION["cart"][$name] = array("id" => $prod, "name" => $_POST["name"], "quantity" => 1, "des" => $_POST["des"]);
foreach ($piid as $value) {
$ab = $value[id];
$qty = $_POST["htop".$ab];
if ($qty > 0) {
$piid[] = array("id" => $row["ID"], "des" => $row["des"], "hid" => $row["hide"]);
$_SESSION["cart"][$name]["top".$value[id]] = array("id" => $value[id], "dec" => $value[des], "qty" => $qty);
}
}
} else {
$name = $_POST["name"];
$name = $name.$$name;
if (isset($_SESSION['cart'][$name]) && ($_SESSION['cart'][$name]['des'] === $_POST['des'])) {
$_SESSION['cart'][$name]['quantity'] += 1;
} elseif (isset($_SESSION['cart'][$name]) && ($_SESSION['cart'][$name]['des'] <> $_POST['des'])) {
$_SESSION[$$name] += 1;
$name = $_SESSION[$$name];
$_SESSION["cart"][$name] = array("id" => $_POST["prod"], "name" => $_POST["name"], "quantity" => 1, "des" => $_POST["des"]);
} else {
$_SESSION["cart"][$name] = array("id" => $_POST["prod"], "name" => $_POST["name"], "quantity" => 1, "des" => $_POST["des"]);
}
}
To avoid confusion in the array when items have different description it will set a multi-dimensional array by using the product's name and an incremental id (where required)
Now my question is how do I get a remove button to work something like this?
I need to pass that sub-array's name/key as a variable so we can then pass that back to the POST method.
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post"
enctype="application/x-www-form-urlencoded">
<button type="submit">Remove
<input type="hidden" name="rprid" value="' .$name. '" />
<button</form></div>
Thanks!
I've managed to figure out the code I need which should be a follows;
foreach($cart as $key => $value)
{
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post" enctype="application/x-www-form-urlencoded"><button type="submit">Remove<input type="hidden" name="rprid" value="' .$key. '" /></form></div>';
}
Thanks for the thoughts all!
Edit: The solution is to use $key => $value that way you can simply use $key to return the key which you are looking at.

Create variable from $_POST array in php

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

json_encode from php array: how do I adjust my php so my array is correct?

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.

editing a value in a multidimentional array in php

I've got a session called Cart_array which holds a multidimensional array in the following way:
$_SESSION['Cart_array'] = array(
1 => array(
"ID" => $pid,
"QTY" => 1
)
);
this is how items are added to the cart session. pid is obtained from another form
if (isset($_POST['pid'])) {
$pid = $_POST['pid'];
if (!isset($_SESSION['Cart_array']) || count($_SESSION['Cart_array']) < 1) { //check if cart session is not set or empty
$_SESSION['Cart_array'] = array(
1 => array(
"ID" => $pid,
"QTY" => 1
)
);
} else {
array_push($_SESSION['Cart_array'], array(
"ID" => $pid,
"QTY" => 1
));
} //end else
} //end if
the user has a form with the following things in a function:
<?php foreach ($_SESSION['Cart_array'] as $eachItem) {
$itemID = $eachItem['ID'];
$itemQty = $eachItem['QTY']; >?
<input class="qty" name="quantity" type="number" value="<?php echo $itemQty;?>" />
<input type="submit" name="qtyChange<?php echo $itemID;?>" value="Change Qty" />
<input name="qtyOfItem" type="hidden" value="<?php echo $itemID?>"/>
}
This form will go through the Cart_array and display the quantity in the cart for every item.
I want the user to be able to change the quantity in the cart for the specific item that they chose when they click the Change Qty button
I'm not sure how to go around doing this?
You could edit the array like this
Your Array
$list = array([0]=>
array(
[ID]=>'XYZ'
[QTY]=>'1'
)
);
my_function()
{
$list=$_SESSION['Cart_array'];
global $list;
$list[0]['QTY'] = '2'; //or this 2 value can be taken from user using jquery
}
my_function();
For the script that this submits to, you want to loop through each item in the cart_array session and find it by that ID then change the quantity for that item.
foreach($_SESSION['cart_array'] as $index => $item){
if($item['ID'] == $_POST['ID']){
$_SESSION['cart_array'][$index]['quantity'] = $_POST['quantity'];
}
}
Just pass your quantity value from the user like this
<?php
$_SESSION['Cart_array'] = array(
1 => array(
"ID" => $pid,
"QTY" => 1
)
);
$_SESSION['Cart_array'][1]['QTY']=30;//Relaces the quantity from 1 to 30

Find sum of all keys in Session array

I am using a form to create several arrays in a Session. Each time the form is submitted a new _SESSION['item'][] is made containing a new array. The code for this:
$newitem = array (
'id' => $row_getshoppingcart['id'] ,
'icon' => $row_getimages['icon'],
'title' => $row_getimages['title'],
'medium' => $row_getshoppingcart['medium'],
'size' => $row_getshoppingcart['size'],
'price' => $row_getshoppingcart['price'],
'shipping' => $row_getshoppingcart['shipping']);
$_SESSION['item'][] = $newitem;
There could be any number of item arrays based on how many times the user submits the form. How can I get the total of the key 'price' from every item in the entire session and echo it on the page?
Thank you in advance for your time. I really appreciate it.
Try this (untested):
$sum = 0;
foreach ($_SESSION['item'] as $item)
$sum += $item['price'];
echo $sum;
Loop through them:
$total = 0;
foreach($_SESSION['item'] as $item) {
$total += $item['price'];
}
echo $total;

Categories