Unable to change session variables in zend .. is the approach wrong? - php

Here are the steps that i have followed till now :
Firstly i have initialized the namespace for my session
$guest_events = new Zend_Session_Namespace('guest_events');
then added an array to the session
$guest_events-> events = array();
then i added some events to the array.
which looks like :
Array
(
[amount_0] => 1
[event_id_0] => 69
[event_title_0] => Sunday Collection
[amount_1] => 11
[event_id_1] => 78
[event_title_1] => Test event
)
Now in my another controller when i try to implement edit amount functionality through ajax :
$event_id = $this-> getRequest()-> getParam('event_id');
$edit_amount = $this-> getRequest()-> getParam('edit_amount');
$event_title = $this-> getRequest() -> getParam('event_title');
$guest_events = new Zend_Session_Namespace('guest_events');
$event_array = $guest_events-> events;
for ($i = 0; $i < 5; $i ++)
{
if (array_key_exists('event_id_'.$i, $event_array))
{
if ($event_array['event_id_'.$i]==$event_id && $event_array['event_title_'.$i]==$event_title)
{
// unset the amount and replace with new one
unset($guest_events-> events-> amount_0);
$guest_events-> events-> amount_0 = $edit_amount;
}
}
}
i have tried everything but the session variables remain unchanged .. can anyone tell why ?? :(

If the element events is an array in your Zend_Session_Namespace object, then you should be setting it like this:
$guest_events-> events['amount_0'] = $edit_amount;
instead of like:
$guest_events-> events-> amount_0 = $edit_amount;
Also, since you are in a loop which finds the correct numeric value, I think it should actually be:
$guest_events-> events['amount_' . $i] = $edit_amount;

I figured out the problem .. it isn't going inside the inner if loop .. i.e :
if ($event_array['event_id_'.$i]==$event_id && $event_array['event_title_'.$i]==$event_title)
{
// unset the amount and replace with new one
unset($guest_events-> events-> amount_0);
$guest_events-> events-> amount_0 = $edit_amount;
}
still cant figure out why this is happening though :/

Related

Unset array element and reseting array values in PHP

So I have 2 files. In file 1 I have a table and there I randomly select some fields and store (store in session) them in an array of 2D arrays. When I click on the cell I send this data to my file 2 where I want to check if I clicked on a randomly selected array or not and if I did, I want to remove this 2D array from an main array.
But as soon as I click on one of the selected arrays, the array crashes.
File 1 PHP stuff immportant for this:
session_start();
$_SESSION['arrays'] = $stack ;
File 2 PHP:
session_start();
if (isset($_SESSION['arrays'])) {
$stack = $_SESSION['arrays'];
for ($i = 0; $i< count($stack);$i++){
if($cooridnates == $stack[$i]){
unset($stack[$i]);
array_values($stack);
$i--;
$Result = true;
break;
}
}
$_SESSION['arrays'] = $stack ;
I am suspecting the error might be in 2 things:
count($stack) used, but I don't believe this is the main reason.
The way I store session.
I have tried using manuals from W3Schools and official PHP website and also SOF, but with no use.
But still, I am not sure if the array_values() and unset() is working correctly since the thing chrashes and I can't test it correctly.
I would appreciate any tips.
You need to assign the result of array_values($stack); back to the $stack variable.
$stack = array_values($stack);
There's also no need to use $i-- when you do this, since you're breaking out of the loop after you find a match.
Instead of a loop, you can use array_search():
$pos = array_search($coordinates, $stack);
if ($pos !=== false) {
unset $stack[$pos];
$Result = true;
$stack = array_values($stack);
$_SESSION['arrays'] = $stack;
}
you can do this like that by using foreach loop:
session_start();
if (!empty($_SESSION['arrays'])) {
foreach( $_SESSION['arrays'] as $key => $val){
if($cooridnates == $val){
unset($_SESSION['arrays'][$key]); // if you want this removed value then assign it a variable before unsetting the array
$Result = true;
break;
}
}
}

Removing a certain number out of a session array in PHP

I have a button next to all my 'shop items' that can remove one of the shop item, however i need it to just remove one, and not rid the entire array of the number, i thought this was possible by using a break statement when i found the number i want to remove, but it removes all of the numbers.
if (isset($_GET['remove']) && isset($_SESSION['shopitems'])) {
if (in_array($_GET['remove'], $_SESSION['shopitems'])) {
for ($i = 0; $i < sizeof($_SESSION['shopitems']); $i++) {
if ($_SESSION['shopitems'][$i] == $_GET['remove']) {
$shopArray = $_SESSION['shopitems'];
if(sizeof($shopArray) == 1) {
$_SESSION['shopitems'] = null;
$_SESSION['added'] = null;
} else {
array_splice($shopArray, $i, $i);
$_SESSION['shopitems'] = $shopArray;
}
break;
}
}
}
}
Here i check if the URL contains the remove variable and the session is set, once i have done this, i check if the array contains the number that is put in the URL, if so i'll start a for loop and check if the key index of the session shop items is equal to the URL variable, if so i want to remove it, however if i use array_splice, suddenly they are all gone, is this because of the function i am using? Or is the break not executing correctly?
Why don't you try array_search() and unset()? It's easier, have a look at the code below and adapt it to your situation:
$array = [1, 5, 6, 12];
$wantToRemove = 5;
$key = array_search($wantToRemove, $array);
unset($array[$key]);
var_dump($array);
You can format your $_SESSION['shopitems'] like this :
$_SESSION['shopitems'] = array (
"item_id" => "item_info",
"item2_id" => "item2_info",
...
)
and do unset($_SESSION['shopitems'][$_GET['remove']]).
Your code could be :
if (isset($_GET['remove']) && isset($_SESSION['shopitems']))
if (isset($_SESSION['shopitems'][$_GET['remove']]))
unset($_SESSION['shopitems'][$_GET['remove']])

Same object property with different values

I have a problem occurring in one function, for me it's strange because I thought that the behaviour of objects were different. The function is:
function getMessages($imapCon)
{
$messageHeaders = array();
$tempObj = new stdClass();
$totalMessages = imap_num_msg($imapCon);
for ($i = $totalMessages; $i > 0; $i--)
{
$headers = imap_headerinfo($imapCon, $i);
$tempObj->Unseen = $headers->Unseen;
$tempObj->fromaddress = $headers->fromaddress;
$tempObj->Date = $headers->Date;
$tempObj->Subject = $headers->Subject;
$tempObj->uid = imap_uid($imapCon, $i);
array_push($messageHeaders, $tempObj);
}
return json_encode($messageHeaders);
}
In the json encoded, I get the same values for all properties (Unseen, fromaddress, Date...). The properties are set correct, but the values are duplicated. Why?
If I do something like:
for ($i = $totalMessages; $i > 0; $i--)
{
$tempObj = new stdClass();
...
array_push($messageHeaders, $tempObj);
unset($tempObj);
}
return json_encode($messageHeaders);
}
declaring the object inside the for, it works. But I believe this is a poor fix and nor the right thing to do...
Creating a new $tempObj inside the loop is the right way. When you add this object into array, it's not copied, but a pointer to it is added into the array. Check this documentation - http://php.net/manual/en/language.oop5.basic.php#example-191 (look at the simple assignment, ignore the $reference variable for now).
So you end up with array containing the whole bunch of links pointing to the same object. But if you create a new $tempObj inside the loop, all objects will be different.
Alternatively, you can do this:
array_push($messageHeaders, clone($tempObj));
but although this will equally work in this case, it may not work if the $tempObj would have more complex structure, such as instances of othe classes as properties of $tempObj.
On a side note, in PHP4 your code would work as you expected as PHP4 was copying actual objects on assignment instead of just pointers as PHP5 does.
It looks like you are just pushing a reference into the $messageHeaders array each time, but you are reassigning the data on the same instance. Not sure where you got the idea that it was wrong to create a new $tempObj on each iteration but that is one way you could solve this. Another way would be to just add to the $messageHeaders array directly like this:
$messageHeaders[] = array(
'Unseen' => $headers->Unseen,
'fromaddress' => $headers->fromaddress,
'Date' => $headers->Date,
'Subject' => $headers->Subject,
'uid' => imap_uid($imapCon, $i)
);

Push item into an array and replace php

i need to make an array like this
$privateMsgIdArray = array("idlistener" => $idlistener, "maxMsgId" => $lastMsgId);
I need to replace the maxMsgId to the corresponding idlistener, and if the idlistener that i pass doesn't not exist to create a new entry inside the array.
I am a but confused on how i am going to extract the maxMsgId value corresponding to an idlistener.
In other words i need to pass new values of idlisteners only once, and replace maxMsgId each time that they are not equal to the corresponing idlistener.
If the idlistener field doesn't exist create it (push into array).
I pass old array into a session and new array in the current run.
After the run i i replace them.
I believe this sounds a bit confusing though.
e.g
We have an array like this already:
[15][200]
next call maxMsgId is 210
array should be
[15][210]
next call we have a new listener id with maxMsgId 30
array should be
[15][210]
[16][30]
You should be able to accomplish this with a quick loop:
// your "new" values
$idListener = 15;
$maxMsgId = 210;
// loop over the array to see if it contains the `idlistener` you want
$end = count($privateMsgIdArray);
for ($i = 0; $i < $end; $i++) {
if ($privateMsgIdArray[$i]['idlistener'] == $idListener) {
// we found it! overwrite the `maxMsgId` field
$privateMsgIdArray[$i]['maxMsgId'] = $maxMsgId;
break;
}
}
if ($i == $end) {
// we reached the end of the array without finding the `$idListener`;
// add a new entry =]
$privateMsgIdArray[] = array(
'idlistener' => $idListener,
'maxMsgId' => $maxMsgId
);
}
This is a rather brute-force approach though and, if efficiency is something you're after, it would be wise to create a "cache"-style method of idlistener values and their index in the $privateMsgIdArray array.
For instance:
// key = idlistener, value = index in `$privateMsgIdArray`
$idCache = array(15 => 0, 16 => 1);
// check if the `$idListener` is in the cache
if (!isset($idCache[$idListener])) {
// it's not; add a new entry
$key = count($privateMsgIdArray);
$privateMsgIdArray[$key] = array(
'idlistener' => $idListener,
'maxMsgId' => $maxMsgId
);
// add the new index into the cache
$idCache[$idListener] = $key;
} else {
// it is in the cache; pull the corresponding index and set the `maxMsgId` =]
$privateMsgIdArray[$idCache[$idListener]]['maxMsgId'] = $maxMsgId;
}
Both of the approaches above could be converted into functions to make things "more portable" too.

Issues with PHP array iteration logic

The logic required in this case might be simple or not, but I couldn't figure it out. So, I am asking for help.
After a query, I get an array that looks a bit like this:
Array=>
[0]=>
['name'] = item1
['id'] = 1
['parent_id'] = 0
[1]=>
['name'] = item2
['id'] = 2
['parent_id'] = 1
[2]=>
['name'] = item3
['id'] = 3
['parent_id'] = 5
Now, I need to make paths for each and every item in this list. The paths would look something like: /item1 for item1 and something like /item1/item2 for item 2.
Note: The items are not necessarily in order. A parent item might come after it's child...
So, basically, I need a loop (probably more than 1), that when it encounters an item, it writes down the item name preceded by a slash. Then, it looks at the parent_id and writes down the parent_id's name preceded by a slash.
Then it looks at the parent's parent_id and writes down that name preceded by a slash. It continues to do this until it encounters a parent_id of 0. At which point, it assigns a value to an array, so something like paths['item2'] = "/item1/item2" and moves on to the next id and repeats!
Thanks for all your help, have a good day!
edit: Fixed the id of item3, all the items are meant to have different id's.
I was asked to improve the question:
The final output array should look a bit like this:
Array=>
["item1"]="/item1"
["item2"]="/item1/item2"
["item3"]="/item5/item3"
The final output would be a html select form with each item as an option, and I need to have it's path associated somehow, either with a hidden field or just through Ajax or something.
edit: I fixed the problem. I just thought I'd write out the solution here in case someone else stumbles across this.
Note: Still, not exactly sure how it works, but it works! It might be inefficient, I don't know.
function getCollPath($proj_list, $length){
$total_path = "";
$paths = array();
for ($j = 0; $j < $length + 1; $j++){
if (isset($proj_list[$j])){
$id = $j;
$name = $proj_list[$j]['name'];
$total_path = getItemPath($proj_list, $id, NULL);
$paths[$name] = $total_path;
}
}
return $paths;
}
function getItemPath($proj_list, $current_id, $path){
$current_parent_id = $proj_list[$current_id]['parent_id'];
$current_name = $proj_list[$current_id]['name'];
$current_path = "/".$current_name;
if ($current_parent_id == 0){
if (isset($path)){
return $current_path.$path;
}
else{
return $current_path;
}
}
else{
if (!isset($path)){
$path = $current_path;
}
return getItemPath($proj_list, $current_parent_id, $path);
}
}
A recursive function. It looks out for array element with id = child.parent_id. Then it calls self with the current parent_id as parameter until a element with parent_id = "" or "0" is reached. It should return a segment of the breadcrumb to the parent call, so the original call gets the whole route

Categories