I have an array from a MySQL query of ID numbers that I'm trying to add to a Session Array that is already created. For some reason, my code is adding an array inside the Session Array already in place rather than just adding the ID numbers to the Session. What is causing this to happen?
Here is my PHP...
//Find members of this group and create an array to add to cart
$deletedgroupmembersquery = "SELECT * FROM groupmember WHERE group_id='$groupid'";
$deletedgroupmembers = mysql_query($deletedgroupmembersquery) or die('SQL Error :: '.mysql_error());
if (mysql_num_rows($deletedgroupmembers) > 0) {
$groupmembers = mysql_num_rows($deletedgroupmembers);
$cart = array();
while(($deletedmembersrow = mysql_fetch_assoc($deletedgroupmembers))) {
$cart[] = $deletedmembersrow['contact_id'];
}
//Add the array to the cart session
if (isset($cart)) {
$_SESSION['cart'] = array();
array_push($_SESSION[cart],$cart);
} else {
}
Here is the session the above code is creating..
Array ( [cart] => Array ( [0] => Array ( [0] => 1362 [1] => 1371 [2] => 2241 ) )
Thanks for any help.
$cart is already an array. When you do:
array_push($_SESSION[cart],$cart);
you're pushing it as a sub-array of $_SESSION['cart']. I think you just want:
$_SESSION['cart'] = $cart;
You're defining $cart as an array before you push it into $_SESSION[cart]...so you're pushing an array into an array. Try something like this:
if (!empty($cart)) {
$_SESSION['cart'] = array();
foreach ($cart AS $item) {
array_push($_SESSION['cart'], $item);
}
}
You can also just place the array_push inside your while(), and stick the $_SESSION['cart'] = array() before the while(), and it will achieve the same thing.
Related
I wrote a function where I get array of marks that i need to post to my database..
My function stores it in a filed row like:
And I need to pull just one per column individually like:
Here is my api call..
public function generate(Map $seatMap)
{
$layout = $seatMap->getSeatLayout();
$seats = [];
$layoutArray = json_decode($layout, true);
$columns = range('A', 'Z');
foreach($layoutArray as $index => $result)
{
$columnLetter = $columns[$index];
$letters = str_split($result);
$letterIndex = 1;
foreach($letters as $letterIndex => $letter) {
switch($letter) {
case 'e':
$seats[] = $columnLetter . $letterIndex;
$letterIndex++;
}
}
}
foreach($seats as $seat => $result) {
$result = new Seat();
$result->setName(json_encode($seats));
$this->em->persist($result);
$this->em->flush();
}
}
Any suggestions?
I think that problem is in the part where I need to store it to database..
If I understand you correctly, your issue is here:
foreach($seats as $seat => $result) {
$result = new Seat();
$result->setName(json_encode($seats));
$this->em->persist($result);
$this->em->flush();
}
}
You're indeed creating new Seat instance for every seat, but in this line:
$result->setName(json_encode($seats));
you still assign all (encoded) seats to every instance of Seat. What you want is to assign only the seat from current loop iteration, which is represented by $result variable.
So try with:
$result->setName($result);
You do not need json_encode here too.
If your array is like you say it it then try this
foreach($seats as $seat) {
$result = new Seat();
$result->setName($seat);
$this->em->persist($result);
$this->em->flush();
}
I'am trying to fetch a session variable if the user is a guest. The variable is called "cart" and is set like this:
$product = new Collection((object) [
'product_id' => $request->pId,
'amount' => $request->amount,
'variations' => $variations
]);
Session::push('cart', $product);
Then I later fetch it:
if(Auth::check()){
$cartProducts = ShoppingCartItem::where('user_id', '=', Auth::user()->id)->get();
}else{
$cartProducts = Session::get('cart');
}
foreach($cartProducts as $product){
dd($product);
$totalAmount += $product->amount;
$totalPrice += (PriceHelper::getProductPrice($product->product->id, $product->amount));
}
The problem here is that dd($product) still outputs an array (the session variable array I assume) which means that for example $product->amount does not exist.
This is the output from dd($product):
You can either access the values using get():
foreach ($cartProducts as $product) {
$totalAmount += $product->get('amount');
$totalPrice += PriceHelper::getProductPrice($product->get('product_id'), $product->get('amount'));
}
or as an array:
foreach ($cartProducts as $product) {
$totalAmount += $product['amount'];
$totalPrice += PriceHelper::getProductPrice($product['product_id'], $product['amount']);
}
or you could use sum() on the collection instead of using foreach:
$cartProducts = collect(Session::get('cart'));
$totalAmount = $cartProducts->sum('amount');
$totalPrice = $cartProducts->sum(function ($product) {
return PriceHelper::getProductPrice($product['product_id'], $product['amount']);
});
Edit
For a quick fix if you need $product to be an object you could do something like:
$cartProducts = collect(Session::get('cart'))->map(function ($item) {
return (object)$item->toArray();
});
Hope this helps!
This question already has an answer here:
Cakephp add function if id exists edit else create
(1 answer)
Closed 6 years ago.
I want to update the record if the ID is exists in my database. If ID not exists create record. This is my code in my Controller add function
public function add () {
$googleCategory = $this->request->data;
foreach ($googleCategory as $key => $value) {
if(empty($value['category'])){
unset($value);
}
$this->AccountShopMeta->create();
$data['shop_id'] = $value['shop_id'];
$data['name'] = $value['category'];
$data['value'] = $value['url_key'];
$data['tag'] = '';
if($this->AccountShopMeta->save($data)){
$account_shop_meta = $this->AccountShopMeta->read();
$this->set($account_shop_meta);
$this->set('_serialize', array_keys($account_shop_meta));
}
}
}
if i understood what you are asking may be this will help you. Do not use Create. if id exist in given array ,updatation automatically will be done on that ID. Otherwise new row will be created.
public function add () {
$googleCategory = $this->request->data;
foreach ($googleCategory as $key => $value) {
if(empty($value['category'])){
unset($value);
}
if(!empty($value[id])){
$data['id']=$value[id];
}
$data['shop_id'] = $value['shop_id'];
$data['name'] = $value['category'];
$data['value'] = $value['url_key'];
$data['tag'] = '';
if($this->AccountShopMeta->save($data)){
$account_shop_meta = $this->AccountShopMeta->read();
$this->set($account_shop_meta);
$this->set('_serialize', array_keys($account_shop_meta));
}
}
}
I suppose if id not exists it comes as empty, in such case add following conditions within foreach and at least above save action:
foreach ($googleCategory as $key => $value) {
if(isset($value['id']) && !empty($value['id'])){
$this->AccountShopMeta->id = $value['id'];
// your remaining code within loop here
//
}
}
Do not forget to send data for id form your view(form) if exists..
In SilverStripe 3.1 I have a function that loops through an array and outputs its contents.
The output it gives me is:
Layout: John
Strategy: John
Management: Martin
In this example John has more than one job.
I would like to group the jobs if a person has more than one job.
This is my desired Output:
Layout and Strategy: John
Management: Martin
//$InfoFieldArray = array('Layout' => 'John', 'Strategy' => 'John', 'Management' => 'Martin');
public function createInfoFields($InfoFieldArray){
$Info = ArrayList::create();
foreach($InfoFieldArray as $key => $value ){
$fields = new ArrayData(array('FieldName' => $key, 'Value' => $value));
$Info->push($fields);
}
return $Info;
}
How do I alter my function to achieve my desired output?
One possible solution to that is by restructuring the data before adding it to the ArrayList.
public function createInfoFields($InfoFieldArray)
{
$info = array();
foreach ($InfoFieldArray as $job => $person)
{
if (!isset($info[$person]))
{
$info[$person] = array();
}
$info[$person][] = $job;
}
$result = ArrayList::create();
foreach ($info as $person => $jobs)
{
$fields = new ArrayData(array('FieldName' => implode(' and ', $jobs), 'Value' => $person));
$result->push($fields);
}
return $result;
}
What I have done is go over the array of jobs and the person assigned and flipped it the other way around, so I have an array of people with a list of jobs. This allows me to then just call implode in PHP, joining the various jobs by the word and.
There are some potential drawbacks, if there are two people named "John", they will be treated as one as I am using the name as the array key.
Also, if there are three jobs for a person, it will list it like "Layout and Strategy and Management". To avoid that, we need to modify the second foreach loop in my code to something like this:
foreach ($info as $person => $jobs)
{
$jobString = null;
if (count($jobs) > 1)
{
$jobString = implode(', ', array_slice($jobs, 0, -1)) . ' and ' . array_pop($jobs);
}
else
{
$jobString = $jobs[0];
}
$fields = new ArrayData(array('FieldName' => $jobString, 'Value' => $person));
$result->push($fields);
}
When there is more than 1 job for a person, we want to implode (glue together) the array pieces for the $jobs array however we don't want the last element at this point. Once array is glued together, we append with with and along with the last item.
I am working on a Perl script, but I am having an issue I can't really overcome. Here is my code:
my #rowses = ();
while ( #list = $sth->fetchrow_array())
{
%row = ();
if($list[30] == 1)
%row = (
cod_cliente => $list[1],
rag_soc => $list[2],
p_iva => $list[11],
IDanagrafica => $list[0],
tabella => $tab,
IDanagraficaE => $list[0],
tabellaE => $tab,
checkbox => "checked",
);
$LOL = \%row;
print $cgi->p($LOL);
}
else
{
%row = (
cod_cliente => $list[1],
rag_soc => $list[2],
p_iva => $list[11],
IDanagrafica => $list[0],
tabella => $tab,
IDanagraficaE => $list[0],
tabellaE => $tab,
checkbox => "",
);
$LOL = \%row;
print $cgi->p($LOL);
}
push (#rowses, \%row);
}
$template->param(table => \#rowses);
$template->param(tab => $tab);
When I try to print, for debugging, the reference to a row ($LOL), it prints nothing, and when I print the reference at #rowses, it is an array full of all the same hash, the last one the fetched by from the statement.
The weird is, if I print a hash row per time, without referencing it, it prints them well, and all of them.
I am doing that for passing the array reference, containing all the hashes, to a TMPL_LOOP, and print them; but it print a long list of only the last row fetched.
Thanks in advance to everyone who will help me.
Your %row is the same variable for each iteration of the while loop. You store just the reference to it in #rowses, which means if you change %row, all the references point to the changed hash. You should define a new %row for each iteration of the loop, e.g. by using
my %row;
indead of
%row = ();
Why $LOL is not printed: If the first argument to p is a hash reference, it is interpreted as the attributes of the <p>.