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.
Related
I am trying to merge two arrays, but getting NULL. Below is my code
$a = 1;
foreach($codes as $values) {
$id = $values['id'];
$post_data = array (
"id" => $id,
"name" => $this->input->post('Name'),
"from_date" => $this->input->post('FromDate'),
"to_date" => $this->input->post('ToDate')
);
$this->data['output' . $a++] = $this->my_modal->simple_post($post_data);
}
$this->data['output'] = array_merge($this->data['output1'], $this->data['output2']);
var_dump($this->data['output']);
Any suggestions will be appreciated. Thanks..
You have to delete the first parameter (NULL) of array_merge();
And what is $this->input->$id? Don't you mean $id?
And in this environment, it's better to use array_push();:
$a = 1;
$this->data['output'] = array();
foreach($codes as $values)
{
$id = $values['id'];
$post_data = array (
"id" => $id,
"name" => $this->input->post('Name'),
"from_date" => $this->input->post('FromDate'),
"to_date" => $this->input->post('ToDate')
);
$new_data = $this->my_modal->simple_post($post_data);
array_push($this->data['output'], $new_data);
}
var_dump($this->data['output']);
$a = 1;
$this->data['output'] = array();
foreach($codes as $values){
$id = $values['id'];
$post_data = array (
"id" => $id,
"name" => $this->input->post('Name'),
"from_date" => $this->input->post('FromDate'),
"to_date" => $this->input->post('ToDate')
);
$data['output2']= $this->my_modal->simple_post($post_data);
if(count($this->data['output1']) > 1) {
$this->data['all'] = array_merge($this->data['output1'],$data['output2']);
}else {
$this->data['all'] = $data['output1'];
}
}
print_r($this->data['all']);
Your code is perfectly right, the only problem is that you start the counter with $a = 1, and do $a++ which will result in 2. So the output1 does not exist. However if you write (notice the subtle change):
$a = 1;
foreach($codes as $values) {
$id = $values['id'];
$post_data = array (
"id" => $id,
"name" => $this->input->post('Name'),
"from_date" => $this->input->post('FromDate'),
"to_date" => $this->input->post('ToDate')
);
$this->data['output' . $a] = $this->my_modal->simple_post($post_data); // $a = 1 now
$a++; // $a becomes 2 here
}
$this->data['output'] = array_merge($this->data['output1'], $this->data['output2']);
var_dump($this->data['output']);
I am trying get user value from multidimensional array as
$array = array();
$array["id"] = "1";
$array["name"] = "name1";
$array["country"] = "country1";
$array["id"] = "2";
$array["name"] = "name2";
$array["country"] = "country2";
$array["id"] = "3";
$array["name"] = "name3";
$array["country"] = "country3";
$array["id"] = "4";
$array["name"] = "name4";
$array["country"] = "country4";
foreach($array as $e){
print_r($e);
}
It return me 4name4country4 only
I need to fetch rows like
foreach($array as $e){
$id=$e['id'];
$name=$e['name'];
$country=$e['country'];
echo $id.'/'.$name.'/'.$country.'<br>';
}
but this gives me error as Illegal string offset 'id'
from what I understood about array this should return all values, Please see why this simple array is not working and suggest any way to do it
Currently you are overwriting the keys. Need to add the keys properly. You have to build the array like -
$array[0]["id"] = "1";
$array[0]["name"] = "name1";
$array[0]["country"] = "country1";
$array[1]["id"] = "2";
$array[1]["name"] = "name2";
$array[1]["country"] = "country2";
OR
$array = array(
0 => array('id' => 1, 'name' => 'name1', 'country' => 'country1'),
1 => array('id' => 2, 'name' => 'name2', 'country' => 'country2'),
);
Instead, do it like so you won't have to give array keys manually
$array = array();
$array[] = array("id" => 123, "name" => "Your name", "country" => "UK");
$array[] = array("id" => 1342, "name" => "Your name 2 ", "country" => "UK");
then in foreach do this
foreach($array as $key => $val){
echo $key. ": ".$val['id']. " " . $val['name'];
}
You have to create the multidimensional array like this, right now you're overwriting the array multiple times.
$arrays = [
[0]=>
["id"] => "1",
["name"] => "name1",
["country"] => "country1"
],
[1]=>[
...
]
];
foreach($arrays as $array){
$id=$array['id'];
$name=$array['name'];
$country=$array['country'];
echo $id.'/'.$name.'/'.'$country'.'<br>';
}
I have this post array
Array (
[imgurl_3] => http://localhost/wordpress/wp-content/uploads/2014/03/05-239x300.jpg
[imgtekst_3] => Write a text for the slide
[imgurl_4] => http://localhost/wordpress/wp-content/uploads/2014/03/img_2184-300x225.jpg
[imgtekst_4] => Write a text for the slide
[update_gallery] => Save changes )
The numbers in the end of the imgurl and imgtekst are dynamic. So.
I want to pair the imgurl_3 & imgtekst_3, and so on. To update into a database.
Any smart PHP functions for this?
Thanks
$array = [
'imgurl_3' => 'http://localhost/wordpress/wp-content/uploads/2014/03/05-239x300.jpg',
'imgtekst_3' => 'Write a text for the slide',
'imgurl_4' => 'http://localhost/wordpress/wp-content/uploads/2014/03/img_2184-300x225.jpg',
'imgtekst_4' => 'Write a text for the slide',
'update_gallery' => 'Save changes'
];
$output = [];
foreach ($array as $key => $item) {
$intKey = filter_var($key, FILTER_SANITIZE_NUMBER_INT);
if ($intKey) {
$key = preg_replace('/_\d/', '', $key);
$output[$intKey][$key] = $item;
}
}
print_r($output);
You could use a for loop and select correlated entries:
for($i = 0; $i < $whatever; $i++) {
if(array_key_exists('imgurl_' . $i, $array)) {
$value = $array['imgurl_' . $i];
$value2 = $array['imgtekst_' . $i];
}
$sqlQuery = '<UPDATE using $value and $value2>';
}
How can I merge this three arrays
$name ={"Tom", "John", "David"};
$v1 = {"Tom":100, "David":200};
$v2 = {"John":500, "Tom":400};
into one multidimensional associative array in two different ways?
One way is the key order should be same as that of array "name".
$name_merged_original_order = array (
"Tom" => Array(
"v1" => 100,
"v2" => 400
),
"John" => Array(
"v1" => "N/A",
"v2" => 500
),
"David" => Array(
"v1" => 100,
"v2" => "N/A"
)
)
Another ways is the alphabetical of array "name":
$name_merged_asc = array (
"David" => Array(
"v1" => 100,
"v2" => "N/A"
),
"John" => Array(
"v1" => "N/A",
"v2" => 200
),
"Tom" => Array(
"v1" => 100,
"v2" => 400
),
)
The tricky part is that array "v1" and "v2" is not ordered as the key of "name." They also don't have all keys as in "name." Thanks!
It's not tested and the easiest solution:
$name_merged_original_order = array();
foreach($name as $key){
$name_merged_original_order[$key] = array();
if(array_key_exists($key, $v1)){
$name_merged_original_order[$key]['v1'] = $v1[$key];
}
else{
$name_merged_original_order[$key]['v1'] = 'N/A';
}
if(array_key_exists($key, $v2)){
$name_merged_original_order[$key]['v2'] = $v2[$key];
}
else{
$name_merged_original_order[$key]['v2'] = 'N/A';
}
}
sort($name);
$name_merged_asc = array();
foreach($name as $key){
$name_merged_asc[$key] = array();
if(array_key_exists($key, $v1)){
$name_merged_asc[$key]['v1'] = $v1[$key];
}
else{
$name_merged_asc[$key]['v1'] = 'N/A';
}
if(array_key_exists($key, $v2)){
$name_merged_asc[$key]['v2'] = $v2[$key];
}
else{
$name_merged_asc[$key]['v2'] = 'N/A';
}
}
As I understand you would like something like that:
$name = array("Tom", "John", "David");
$result = array();
$v1 = array("Tom" => "200", "John" => "100", "David" => "10");
$v2 = array("Tom" => "254", "David" => "156");
$vars = array("v1", "v2");
foreach($name as $n)
{
$result[$n] = array();
foreach($vars as $v)
{
if(array_key_exists($n, ${$v}))
$result[$n][$v] = ${$v}[$n];
}
}
I hope $result is what you need.
For Example, you have these arrays:
<?php
$FirstArrays = array('a', 'b', 'c', 'd');
$SecArrays = array('1', '2', '3', '4');
1)
foreach($FirstArrays as $index => $value) {
echo $FirstArrays[$index].$SecArrays[$index];
echo "<br/>";
}
or 2)
for ($index = 0 ; $index < count($FirstArrays); $index ++) {
echo $FirstArrays[$index] . $SecArrays[$index];
echo "<br/>";
}
Assume from your comments you only want items that match in all 3 arrays:
for( $i=0; $i< count($name) ; $i++){
if( !empty( $v1[ $name[$i]]) && !empty( $v2[ $name[$i]]) ){
$newArray[$name[$i]]= array( 'v1'=> $v1[ $name[$i]], 'v2'=> $v2[ $name[$i]]):
}
}
To sort:
asort($newArray);
Right now i got an array which has some sort of information and i need to create a table from it. e.g.
Student{
[Address]{
[StreetAddress] =>"Some Street"
[StreetName] => "Some Name"
}
[Marks1] => 100
[Marks2] => 50
}
Now I want to create database table like which contain the fields name as :
Student_Address_StreetAddress
Student_Address_StreetName
Student_Marks1
Student_Marks2
It should be recursive so from any depth of array it can create the string in my format.
You can use the RecursiveArrayIterator and the RecursiveIteratorIterator (to iterate over the array recursively) from the Standard PHP Library (SPL) to make this job relatively painless.
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$keys = array();
foreach ($iterator as $key => $value) {
// Build long key name based on parent keys
for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
$key = $iterator->getSubIterator($i)->key() . '_' . $key;
}
$keys[] = $key;
}
var_export($keys);
The above example outputs something like:
array (
0 => 'Student_Address_StreetAddress',
1 => 'Student_Address_StreetName',
2 => 'Student_Marks1',
3 => 'Student_Marks2',
)
(Working on it, here is the array to save the trouble):
$arr = array
(
'Student' => array
(
'Address' => array
(
'StreetAddress' => 'Some Street',
'StreetName' => 'Some Name',
),
'Marks1' => '100',
'Marks2' => '50',
),
);
Here it is, using a modified version of #polygenelubricants code:
function dfs($array, $parent = null)
{
static $result = array();
if (is_array($array) * count($array) > 0)
{
foreach ($array as $key => $value)
{
dfs($value, $parent . '_' . $key);
}
}
else
{
$result[] = ltrim($parent, '_');
}
return $result;
}
echo '<pre>';
print_r(dfs($arr));
echo '</pre>';
Outputs:
Array
(
[0] => Student_Address_StreetAddress
[1] => Student_Address_StreetName
[2] => Student_Marks1
[3] => Student_Marks2
)
Something like this maybe?
$schema = array(
'Student' => array(
'Address' => array(
'StreetAddresss' => "Some Street",
'StreetName' => "Some Name",
),
'Marks1' => 100,
'Marks2' => 50,
),
);
$result = array();
function walk($value, $key, $memo = "") {
global $result;
if(is_array($value)) {
$memo .= $key . '_';
array_walk($value, 'walk', $memo);
} else {
$result[] = $memo . $key;
}
}
array_walk($schema, 'walk');
var_dump($result);
I know globals are bad, but can't think of anything better now.
Something like this works:
<?php
$arr = array (
'Student' => array (
'Address' => array (
'StreetAddress' => 'Some Street',
'StreetName' => 'Some Name',
),
'Marks1' => array(),
'Marks2' => '50',
),
);
$result = array();
function dfs($data, $prefix = "") {
global $result;
if (is_array($data) && !empty($data)) {
foreach ($data as $key => $value) {
dfs($value, "{$prefix}_{$key}");
}
} else {
$result[substr($prefix, 1)] = $data;
}
}
dfs($arr);
var_dump($result);
?>
This prints:
array(4) {
["Student_Address_StreetAddress"] => string(11) "Some Street"
["Student_Address_StreetName"] => string(9) "Some Name"
["Student_Marks1"] => array(0) {}
["Student_Marks2"] => string(2) "50"
}
function getValues($dataArray,$strKey="")
{
global $arrFinalValues;
if(is_array($dataArray))
{
$currentKey = $strKey;
foreach($dataArray as $key => $val)
{
if(is_array($val) && !empty($val))
{
getValues($val,$currentKey.$key."_");
}
else if(!empty($val))
{
if(!empty($strKey))
$strTmpKey = $strKey.$key;
else
$strTmpKey = $key;
$arrFinalValues[$strTmpKey]=$val;
}
}
}
}