add value into userdata array - php

I thought this would be simple but I cant seem to get it to work. All I want to do is to add a value into a userdata array. If a value is already in the viewed_news_items array I do not want to replace it.
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true,
'viewed_news_items' => array()
);
$this->session->set_userdata($data);
insert value into viewed_news_items array
$a = array($desk_id => $desk_id);
$this->session->set_userdata('viewed_news_items', $a);

You're using $desk_id as both the key and value, meaning unless you already have the value of $desk_id, you won't be able to look it up in the array.
Instead of this:
$a = array($desk_id => $desk_id);
You probably wanted to do this:
$a = array('desk_id' => $desk_id);
That is, use the string 'desk_id' as the key whose corresponding value is $desk_id.
Is there a way to have the 'desk_id' just as an auto number so each time the code is executed another value is added instead of replacing 'desk_id'?
You can push items onto the end of an array via array_push($array, $value) or $array[] = $value. PHP will automatically assign the next numeric ID as the index for the new array element.
In your current scenario, you'll have to pull the existing list of IDs out of the session, append an ID to it, and then put it back into the session:
# pull the existing IDs out of the session
$viewed_news_items = $this->session->userdata('viewed_news_items');
# on first load, the array may not be initialized
if (!is_array($viewed_news_items))
$viewed_news_items = array();
# append $desk_id to the list of viewed items
$viewed_news_items[] = $desk_id;
# put the new list back into the session
$this->session->set_userdata('viewed_news_items', $viewed_news_items);

invoke the type of data you retrieved from session
and use it as you want.
$ID = 123;
$data = (array)$this->session->userdata("session_name");
$data[] = $ID;
$this->session->set_userdata("session_name",$data);

Related

merge php arrey on action url get request

I have an IP phone that through 2 action urls makes a get request to my web server.
action urls:
http://192.168.25.126/action.php?ID=$call_id&remote=$display_remote
http://192.168.25.126/action.php?ID=$call_id&extension=$active_user
192.168.25.126 is the web server
action.php is printing to a log file the request
$call_id is a unique ID that the phone is giving to the current session
$remote is the caller's number
$extension is the ip phone extension number
on the server side I have the action.php that prints in a log file the requests through this simple line
<?php
file_put_contents("/tmp/post.log",print_r($_GET,true), FILE_APPEND));
?>
checking the log I can view the expected request
tail -f /tmp/post.log
Array
(
[ID] => 9
[remote] => +39123456789
)
Array
(
[ID] => 9
[extension] => 235
)
How can I merge in tmp.log the arreys with same ID like this?
Array
(
[ID] => 9
[remote] => +39123456789
[extension] => 235
)
pay attention that the first arrey is generated on the ringing event and the second arrey is generated when I pickup the phone(or better to say when a call in enstablished)so in a second moment
I cannot do this with only one action url like this
http://192.168.25.126/action.php?ID=$call_id&remote=$display_remote&extension=$active_user
due a limitation of my ip phone so I have to merge the 2 arreys. and if possible I would like,but this is not really necessary, that the log is printed only if the first arrey with same ID exist(so the log will appears only if an incoming call is answered and not when I make a call).
I'm a senior IT not a php coder so just want a suggestion to write the loop.. many thanks
From what I'm understanding this should do what you need - expecting IDs to be unique.
<?php
// get data from log
$fileData = file_get_contents("/tmp/post.log");
$data = json_decode($fileData, true); // make an array out of the json
// $data will now be something like this:
# $data = [["ID" => 9,"remote" => "+39123456789"],["ID" => 10,"remote" => "+41123456789"]];
// mocking input data
# $_GET = ['ID' => 10, 'otherparam' => 'bar'];
$key = array_search($_GET['ID'], array_column($data, 'ID')); // search for pre-saved data
if($key) { // an item with $ID was found -> merge new data
$item = array_merge($data[$key], $_GET);
$data[$key] = $item; // overwrite existing item with this ID
} else {
$item = $_GET; // create a new item, since we haven't found one
$data[] = $item; // append to data
}
file_put_contents("/tmp/post.log",json_encode($data,true))); // don't append, write the whole dataset
If the IDs are not unique, we could just grab the last added one (via end(), check if IDs match and merge there:
end($data); // set pointer to the end
$key = key($data); // get the key of the last element
if($data[$key]['ID']==$_GET['ID']) {
$item = array_merge($data[$key], $_GET); // merge old and new data
$data[$key] = $item; // overwrite item
}
EDIT:
If you only need the last call, we don't need to re-save the non-matching arrays, so this adapted code should do:
<?php
$fileData = file_get_contents("/tmp/post.log");
$data = json_decode($fileData, true);
// $data will now be something like this:
# $data = ["ID" => 9,"remote" => "+39123456789"]; // note, this time it's a one-dimentional (but assoc) array.
// mocking input data
# $_GET = ['ID' => 9, 'otherparam' => 'bar'];
// check if we have pre-saved data, that has an 'ID' and that matches our current one:
if(is_array($data) && isset($data['ID']) && $data['ID']==$_GET['ID']) { // the saved $ID was found -> merge new data
$data = array_merge($data, $_GET);
} else {
$data = $_GET; // create a new item, since we haven't found one
}
file_put_contents("/tmp/post.log",json_encode($data,true))); // don't append, write the whole dataset
Disclaimer: This code has no error checking whatsoever and will throw errors on a blank log (because json_decode will fail if there's no data yet), has some security issues (using $GET without sanitizing and writing that to a file...), doesn't test for proper input (what if no ID is sent), etc...

Array_push pushes invisible element, and only works on second push

I had a problem with my array_push, that i noticed.
So what i'm doing.:
I have a site, where there are some buttons with a specific value.
Each value is getting fetched from a database.
I have a session called test, that get's converted to an array(to store multiple in the same array)
Everytime one of the buttons are clicked, the value for that specific button, is getting pushed to the array.
But, i can ONLY see that it has been pushed at the second try.
[test] => Array( [0] => 21304 )
This is what i see, after second try. But my array count, says that there are 2 elements, in that array.
Here is my code:
if(isset($_POST['process'])) {
if(!isset($_SESSION['test'])) {
$_SESSION['test'] = array();
$array_merge = array_push($_SESSION['test'], $_POST['process']);
}
}
The $_POST['process'] is the button with the unique value.
Can somebody maybe see what I'm doing wrong here?
Kind regards
You are only adding to the $_SESSION['test'] array if $_SESSION['test'] was not previously set.
So you need to always add an occurance to the session array and only initialise the session array if it was not previously set
session_start();
// ...
if(isset($_POST['process'])) {
if(!isset($_SESSION['test'])) {
$_SESSION['test'] = array();
}
$_SESSION['test'][] = $_POST['process'];
}
NOTE from the manual
If you use array_push() to add one element to the array, it's better to use $array[] = because in that way there is no overhead of calling a function.

How to delete duplicate data as per key value using PHP

I need some help. I need to remove duplicate data as per key value using PHP. I am explaining my code below.
$orginalArr = array(
array("id"=>1,"name"=>"Raj"),
array("id"=>1,"name"=>"Raj"),
array("id"=>2,"name"=>"Ram"),
array("id"=>2,"name"=>"Ram"),
array("id"=>3,"name"=>"Rahul")
);
echo json_encode($orginalArr);
Here I need to remove the data as per id, meaning if id value is same then one set of data will be removed. Please help me.
Just iterate through values and push it to the new array.
Example:
<?php
$orginalArr=array(array("id"=>1,"name"=>"Raj"),array("id"=>1,"name"=>"Raj"),array("id"=>2,"name"=>"Ram"),array("id"=>2,"name"=>"Ram"),array("id"=>3,"name"=>"Rahul"));
$newArray = array();
foreach ( $orginalArr as $arr )
$newArray[$arr['id']] = array(
'id' => $arr['id'],
'name' => $arr['name']);
echo json_encode(array_values($newArray));
?>

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.

Retrieving array/sub-array name for use in php

I have a multi-dimensional array of databases, which was generated from my server:
// place db tables into array
$da_db = array(
'test' => array(
// test.users
'users' => array('fname','lname','info'),
// test.webref_rss_details
'webref_rss_details' => array('id','title','link','description','language','image_title','image_link','item_desc','image_width','image_height','image_url','man_Edit','webmaster','copyright','pubDate','lastBuild','category','generator','docs','cloud','ttl','rating','textInput','skipHours','skipDays'),
// test.webref_rss_items
'webref_rss_items' => array('id','title','description','link','guid','pubDate','author','category','comments','enclosure','source','chan_id')
),
'db_danaldo' => array(
//code here
),
'frontacc' => array(
//code here
)
[array][db][table][field]
As you can see, the database currently populated refers to an RSS project I am working on - one table for Channels, another for Items in that channel, at the moment that is another issue ('Users' table for now is not important)..
what I want to do is to return the array/sub-array names and convert each into variables for use as part of a string in an SQL Query, also need an alias for the tables I need to connect with:
(e.g. SELECT * FROM 'webref_rss_items' WHERE 'chan_id' = 'test.webref_rss_details.id')
where 'webref_rss_items' is a variable, 'chan_id' is a variable and 'test.webref_rss_details.id' are 3 variables in a concatenated string, although I've heard the concatenation in an SQL Query is not good practice, security-wise.. the strange thing is of all of those values, all I can retreive is the deepest level, 'id':
echo "{$da_db['test']['webref_rss_details'][0]}"
but get 'Array' returned or the last value of an array when I try to access the names!!
The reason for this is that the PHP file with the query will be within the 'public' part of the server and would like to have use variables with have no connotation to the original name(s), also it seems more convenient as the variables can be interchangable and I won't be using the same path all the time.
EDIT: My idea is to get key names from ['db'] to ['field']. The closest I have reached is to iterate keys and array_fill in a foreach loop, use range() inside another foreach, array_combine both then var_dump combined array like so:
foreach($da_db['test'] as $key1 => $val) { //put key-names into array1 to use as values
$a = array();
$a = array_fill(0, 1, $key1);
print($key1.'<br />');
}
foreach (range(0, 2) as $number) { //array for numbers to use as keys
$b = array();
$b = array_fill(0, 1, $number);
echo $number.'<br />';
}
$c = array_combine($b, $a); //combine both for new array
print_r($c.'<br />');
I could the use array_slice to get the name I want! (long winded?)
The problem is that the result of this only shows the last key => value; depending on command(print_r, print, echo), it shows:
[2] => webref_rss_items
OR
Array.
I hope that is enough info for now.
I've seen similar questions on here, but normally apply to one value, or one level of an array, but if you have seen this question before please advise and point me in right direction.
Your two top level arrays (db name and table name) are "named-key" arrays. The field level array (value of table name array) is an "integer key" array. PHP automatically adds numerical indexes for arrays that are defined with values only. For "named-key" arrays, you can only access their values by using the key name you defined.
For example:
$array1 = array('zero', 'one', 'two');
echo $array1[2]; // two
$array2 = array('zero' => 'this is zero', 'one' => 'this is one');
echo $array2['zero']; // this is zero
echo $array2[0]; // undefined
PHP provides a function called array_keys() that will return you an integer index array with all the key names. So you access your table array using an integer value, you can do this.
$da_db_test_keys = array_keys($da_db['test']);
echo $da_db_test_keys[1];
Maybe this will help you a little bit. I wasn't 100% on how you planned on accessing the values in your arrays, so if you have any more questions please try to clarify that part.

Categories