I'm trying to add an array into an other array at a specific key. But I have this message :
array_push() expects parameter 1 to be array, null given
I don't understand because in the else I create the array.
$key = $this->input->get('vente');
if(array_key_exists($key,$this->session->userdata('panier'))){
array_push($this->session->userdata('panier')[$key],$toAdd);
}else{
$this->session->userdata('panier')[$key] = array();
array_push($this->session->userdata('panier')[$key],$toAdd);
}
$this->session->userdata return an array but you can't modify it directly. Try this :
<?php
// Storing the session item in a var
$panier = $this->session->userdata('panier');
// $this->session->userdata return null when the item doesn't exist, so we have to check it
if (empty($panier)) $panier = array();
$key = $this->input->get('vente');
if( array_key_exists($key, $panier) ) {
array_push($panier[$key], $toAdd);
} else {
$this->session->userdata('panier')[$key] = array();
array_push($panier[$key], $toAdd);
}
// Then, we set the var in session again !
$this->session->set_userdata('panier', $panier);
Don't hesitate if you need more explanations.
Related
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"]);
I couldn't understand the multidimensional array in PHP properly. I have a CSV file having two columns as shown below:
I am trying to create an array of array, in which each key is a cataegory. However, the value of each key is an array. In this array, each key is company and value is the count of the product. See below the code:
<?php
//array contains value
function contains_value($my_array, $value_search){
foreach ($my_array as $key => $value) {
if ($value === $value_search)
return true;
}
return false;
}
//array contains key
function contains_key($my_array, $key_search){
foreach ($my_array as $key => $value) {
if ($key === $key_search)
return true;
}
return false;
}
$handle = fopen("product_list.csv", "r");
$products = array();
if ($handle) {
while (($line = fgets($handle)) !== false) {
$product = explode(",", $line);
$category = $product[0];
$company = $product[1];
if (contains_key($products, $category)) {
if (contains_value($products, $company)) {
//increase the count of category by 1
$products[$category][$company] = $products[$category][$company] + 1;
} else {
//append new company with count 1
array_push($products[$category], array(
$company,
1
));
}
} else {
//initialize new company with count 1
$products[$category] = array(
$company,
1
);
}
}
fclose($handle);
}
var_dump($products);
?>
I noticed that the var_dump($products) is not showing correction information. I am expecting following kind of result:
I haven't enough reputation to reply, but I think he need counts.
To complete the answer of Alive to Die, more something like this:
if (!array_key_exists($category, $products)) {
products[$category] = [];
}
if (!array_key_exists($company, $products[$category])) {
products[$category][$company] = 0;
}
++$results[$cataegory][$company];
But cleaner ;)
Edit:
If I remember well, his first idea was this:
$products[$category][] = $company;
The code is shorter. Maybe you can combine the two ideas.
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
I am trying to make a dynamic associtive array but the thing is it just save the last key-value pair how can i store all the key-value pairs?
foreach ($_POST as $var => $value) {
// Does the model have this attribute? If not raise an error
if ($model->hasAttribute($var))
$model->$var = $value;
elseif ($profile->hasAttribute($var)) {
$storage = array($var => $value);//associative array
} else {
//var_dump ($var);
$this->_sendResponse(500, sprintf('Parameter <b>%s</b> is not allowed for model <b>%s</b>', $var, $_GET['model']));
}
}
You have only below error:
$storage = array($var => $value);//associative array
This line is creating a new array $storage every time, that's why you are getting only last key value pair.
Try this:
$storage = array();// initialize it as array
$storage[$var] = $value;// assign $value in $key index of $storage
In your code, you're always assigning the $storage to a new array instead of appending it.(Correct me if I'm wrong).
You should append the array this way.
<?php
foreach ($_POST as $var => $value) {
// Does the model have this attribute? If not raise an error
if ($model->hasAttribute($var))
$model->$var = $value;
else if ($profile->hasAttribute($var)) {
if (!is_array($storage))
$storage = [];
$storage[$var] = $value; //associative array
} else {
//var_dump ($var);
$this->_sendResponse(500, sprintf('Parameter <b>%s</b> is not allowed for model <b>%s</b>', $var, $_GET['model']));
}
}
I am pulling data from an api and as such i have a loop that stores some ids into an array.
What i need to do is select all ids from my database and then remove any ids that have been found in the database from the initial array. so i can continue to query the api for ids that i do not have currently.
To make more sense please look below:
$matches = $database->get_results('SELECT match_id FROM `matches` WHERE `order_id`='.$order_id);
if ($matchlist->totalGames !== 0) {
foreach ($matchlist as $key) {
$gameIds[] = $key->matchId;
}
}
I need to remove the ids from $gameIds if they already are stored in the $matches.
Any ideas?
Thanks
I have tried:
$matches = $database->get_results('SELECT `match_id` FROM `matches` WHERE `order_id`='.$order_id);
if ($matchlist->totalGames !== 0) {
foreach ($matchlist as $key) {
$gameIds[] = $key->matchId;
}
$arr_matches = object2array($matches);
$new_array = array_diff($arr_matches, $gameIds);
var_dump($new_array);
}
error:
Catchable fatal error: Object of class stdClass could not be converted to string
Step 1: Change object to array
function object2array($object)
{
if (is_object($object)):
foreach ($object as $key => $value):
$array[$key] = $value;
endforeach;
else:
$array = $object;
endif;
return $array;
}
Step 2:
$arr_matches = object2array($matches)
$new_array = array_diff($arr_matches , $gameIds);
// Will remove all elements contained in $gameIds from $arr_matches array.