I have a add-to-cart form to $_POST all data, and needed to store into a two dimensional array and assign to a session:
for example print_r($_POST) is:
Array("prod"=>"ZIU%3D","price"=>"68.00","alt-variation-1"=>"Red","alt-variation-2"=>"L","qty"=>"1")
to loop each $_POST:
foreach($_POST as $field => $value){
$f[] = $field;
$v[] = $value;
}
I looking for a way to assign above $f and $v into an array such as:
$new_product = array(array($f => $v));
and store in a session like:
$_SESSION['products'] = $new_product;
or any alternate way instead?
$_SESSION['products'][] = $_POST; would append the entire post array to the session products array, but you need to validate the data posted by the user.
A better way would be:
$data = $_POST;
// sanitise and validate $data here
$_SESSION['products'][] = $data;
An example for #HamzaZafeer:
foreach($_SESSION['products'] as $product){
echo $product['price'];
}
you can encode your array to JSON and store it in a session with:
$myJson = json_encode($_POST);
$_SESSION['myJson'] = serialize($myJson);
Related
I need to show data in Attribute and Value form but data is getting is in direct form.
I am trying this
Getting Data in this FOrm
{"FirstName":"sbncf","EmailAddress":"jscn#jnsc.cs","LastName":"jj","Phone":"653736","SearchBy":"jhjnjn"}
But i need in this Form
$data_string = '[{"Attribute":"FirstName","Value":"Bret"},{"Attribute":"LastName","Value":"Lee"},{"Attribute":"EmailAddress","Value":"bret.lee#australia.com"},{"Attribute":"Phone","Value":"8888888888"},{"Attribute":"SearchBy","Value":"Phone"}]';
I am using AJAx and using this
$data_string = json_decode(json_encode($_POST));
enter image description here
You need to store data into an another array, new array must contains Attribute and Value indexes, something like this example:
// testing $_POST data
$post = array();
$post['FirstName'] = 'sbncf';
$post['EmailAddress'] = 'jscn#jnsc.cs';
$post['LastName'] = 'jj';
$newArray = array(); // initialize new array
$i = 0;
foreach ($post as $key => $value) {
$newArray[$i]['Attribute'] = $key;
$newArray[$i]['Value'] = $value;
$i++;
}
//use json_encode here:
$data_string = json_encode($newArray);
echo $data_string;
Result:
[{"Attribute":"FirstName","Value":"sbncf"},{"Attribute":"EmailAddress","Value":"jscn#jnsc.cs"},{"Attribute":"LastName","Value":"jj"}]
include('session.php');
$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
$wishlist = array("$productname" => $productcode);
$_SESSION["wishlist"] = $wishlist;
print_r($_SESSION["wishlist"]);
This code set as an array to a session named "wishlist".
The problem is that the session is being replaced. I want to add to the array if it already exists.
So how can I update my array with new data.
I have tried the following.
$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
$lastsession = $_SESSION["wishlist"];
// CHECK IF SESSION IS EMPTY OR NOT
if(empty($lastsession)) {
$wishlist = array("$productname" => $productcode);
} else {
/*
How Can I Update array ???
*/
}
The array output is like so. It is associated not numeric indexed.
And i want result in single array. Not array in array.
[mobile] => iphone_2
Thank you.
In short, you can do this (if I understand the question correctly):
$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
$lastsession = $_SESSION["wishlist"];
// CHECK IF SESSION IS EMPTY OR NOT
if(empty($lastsession)) {
$wishlist = array("$productname" => $productcode);
} else {
array_push($wishlist, array("$productname" => $productcode));
}
array_push is a function that will add information to the end of an array. In this instance, we are using it to add the product array to the current wishlist.
An alternative simple solution would be:
// create a blank array if the session variable is not created
// array_push requires an array to be passed as the first parameter
$wishlist = isset($_SESSION["wishlist"]) ? $_SESSION["wishlist"] : array();
//$wishlist = $_SESSION["wishlist"] ?? array(); // this is for PHP 7+
array_push($wishlist, array("$productname" => $productcode));
// you can then access each product as:
$wishlist["mobile"];
Or replace line 5 from the above code snippet with the following:
$wishlist[$productname] = $productcode;
This would save you from creating an empty array as in line 3.
The advantage that array_push has over this is that you can add multiple products at once such as:
$products = [$productname1 => $productcode1, $productname2 => $productcode2];
array_push($wishlist, $products);
The one thing I have noticed is that you are setting the session to $lastsession as well as using $wishlist. Try and keep duplicate variables to non-existent.
$_SESSION["wishlist"] = array( 'product1' => 'product1 Name' );
// Initial products in session
$temp_session = $_SESSION["wishlist"];
//store products in wishlist in temp variable
$temp_session['mobile'] = 'iphone_2';
// Add new product to temp variable
$_SESSION["wishlist"] = $temp_session;
//Update session
print_r( $_SESSION["wishlist"] );
Set the wishlist data from the session to variable and then just add the new product to this variable. After that update the wishlist data in the session.
$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
// do the same as: $wishlist = !empty($_SESSION["wishlist"]) ? $_SESSION["wishlist"] : [];
$wishlist = $_SESSION["wishlist"] ?? [];
$wishlist[$productname] = $productcode;
$_SESSION["wishlist"] = $wishlist;
print_r($_SESSION["wishlist"]);
This is my current code, I'm looking for a more efficient way of writing it.
Need something like looping through each variable with a foreach or adding them all to an array somehow, without me having to re-write every variable name.
$formValues = $form_state->getValues();
$relocation = $formValues['relocation'];
$europe = $formValues['europe'];
$twoyears = $formValues['twoyears'];
$realestate = $formValues['realestate'];
$nominated = $formValues['check_nominated_by'];
$nom_comp = $formValues['nom_company'];
$nom_contact = $formValues['nom_contact'];
$nom_email = $formValues['nom_email'];
$contact1 = $formValues['contact1'];
$position1 = $formValues['contact_position1'];
$email1 = $formValues['email1'];
$contact2 = $formValues['contact2'];
$position2 = $formValues['contact2'];
$email2 = $formValues['contact2'];
$contact3 = $formValues['contact3'];
$position3 = $formValues['contact3'];
$email3 = $formValues['contact3'];
tempstore = array();
$tempstore['relocation'] = $relocation;
$tempstore['europe'] = $europe;
$tempstore['twoyears'] = $twoyears;
$tempstore['realestate'] = $realestate;
$tempstore['membertype'] = $membertype;
$tempstore['nominated_by'] = '';
// All other fields need to be in this array too
// But there are a lot of unwanted fields in the $formValues
$_SESSION['sessionName']['formName'] = $tempstore;
Seeing as you know the keys you'd like to keep you can do the following:
<?php
/** The keys you want to keep... **/
$keys_to_keep = [
];
/** Will be used to store values for saving to $_SESSION. **/
$temp_array = [];
/** Loop through the keys/values. **/
foreach ($formValues as $key => $value) {
/** The correct key i.e. the key you'd like to save. **/
if (in_array($key, $keys_to_keep)) {
/** What you wish to do... **/
$temp_array[$key] = $value;
}
}
$_SESSION['sessionName']['formName'] = $temp_array;
?>
What is happening is that you are looping through your $formValues and getting both the keys and values of each pair in the array.
Then an check is being done against your $keys_to_keep to see if the current element is the one you wish to keep, if it is then you save it in to $temp_array.
Reading Material
foreach
in_array
You can use variable variables and a foreach.
Foreach($formValues as $key => $var){
$$key = $var;
}
Echo $relocation ."\n" . $europe;
https://3v4l.org/QeLjp
Edit I see now that your array variable keys are not always the same as the variable name you want.
In that case you can't use the method above.
In that case you need to use list() = array.
List($relocation, $europe) = $formValues;
// The list variables have to be in correct order I just took the first two for demo purpose.
I am trying get a form submitted values in array after isset() but it store only last isset() value in array. What is the right way to get all not null values in array to pass to insert function.
$table = 'booking';
if(isset($_POST['tourID'])){
$data = array('tour_fk' => $this->input->post('tourID'));
}
if(isset($_POST['bookingNumber'])){
$data = array('booking_number' => $this->input->post('bookingNumber'));
}
$query = $this->dashboard_model->insert($table, $data);
The right way is to add new keys to $data instead of reassigning it:
if (isset($_POST['tourID'])){
$data['tour_fk'] = $this->input->post('tourID');
}
if (isset($_POST['bookingNumber'])){
$data['booking_number'] = $this->input->post('bookingNumber');
}
You can achieve like this.Make a array of all not null keys with values.Not need to write isset() for each posted items.Just make use of foreach loop.And achieve your result.
$table = 'booking';
foreach($_POST as $key=>$value) {
if(isset($_POST[$key])) {
$data[$key]=$this->input->post($key);
}
}
//print_r($data);
Here is an example for you..
$array = array('tour_fk'=>1,'booking_number'=>11,'empty_field'=>NULL);
foreach($array as $key=>$value) {
if(isset($array[$key])) {
$data[$key]=$value;
}
}
print_r($data);
Output:
Array ( [tour_fk] => 1 [booking_number] => 11 )//without null values
Array : [{"ID":1},{"ID":2}]
$id=1;
I want to check if $id exists in the array.
Thank you!
You may try Laravel's Collection::contains method, for example:
$collection = collect(json_decode($jsonString, true));
if ($collection->contains(1) {
// Exists...
}
Also, you may use key/value pair like this:
if ($collection->contains('ID', 1) {
//...
}
Also, if you want to get that item from the collection then you may try where like this:
$id = $collection->where('ID', 1)->first(); // ['ID' => 1]
You have a json formatted array and you need to decode it using json_decode first. After that loop the array to check for the id that you want.
So the code should look like this:
$json = '[{"ID":1},{"ID":2}]';
$id = 1;
$data = json_decode($json, true);
foreach($data as $item){
if($item['id'] == $id) {
echo 'it exists';
}
}
Iterate the array using for loop and use the value as a param to json_decode.
$id = 1;
$arr = array('{"ID":1}', '{"ID":2}');
foreach($arr as $val) {
if (in_array($id, json_decode($val, TRUE))) {
echo "id present";
}
}
Try this, if value is exist it will give key of array
$jsondata = '[{"ID":1},{"ID":2}]';
$array = json_decode($jsondata,true);
$key = array_search(1, array_column($array, 'ID'));
Just check if the string is in the json array, with little computation.
I think it's the more efficient way. Check the result here.
<?php
$id = 1;
$array = ['{"ID":1}', '{"ID":2}'];
echo in_array(json_encode(["ID" => $id]), $array) ? 'Yes' : 'No';