In Drupal, I first serialized emails that appear in the body of private messages and stored them is MySQL like this:
function prvtmsg_list($body) {
$notify = array();
if (isset($body->emails)) {
$notify['mid'] = $body->mid;
$notify['emails'] = serialize($body->emails);
}
if (isset($body->vulgar_words) {
$notify['mid'] = $body->mid;
$notify['vulgar_words'] = serialize($message->vulgar_words);
}
if (isset($notify['mid'])) {
drupal_write_record('prvtmsg_notify', $notify);
}
}
When I later try to retrieve them, email userialization fails, I retrieve them like this:
function prvtmsg_list_notify() {
// Select fields from prvtmsg_notify and Drupal pm_message tables
$query = db_select('prvtmsg_notify', 'n');
$query->leftJoin('pm_message', 'm', 'n.mid = m.mid');
$query->fields('n', array('mid', 'emails', 'vulgar_words'));
$query->fields('m', array('mid', 'author', 'subject', 'body', 'timestamp'));
orderBy('timestamp', 'DESC');
$query = $query->extend('PagerDefault')->limit(20);
$result = $query->execute()->fetchAll();
$rows = array();
foreach ($result as $notify) {
$rows[] = array(
$notify->author,
$notify->subject,
implode(', ', unserialize($notify->emails)),
implode(', ', unserialize($notify->vulgar_words)),
);
}
$build = array();
$build['table'] = array(
'#theme' => 'table',
'#header' => array(
t('Author'),
t('Message subject'),
t('Emails captured'),
t('Vulgar Words Captured'),
),
'#rows' => $rows,
);
$build['pager']['#theme'] = 'pager';
return $build;
}
Maybe the way I serialized the emails is wrong? because:
dpm(unserialize($notify->emails);
gives Array, Array, Array - which means:
Array(
[0] => Array() [1] => Array() [2] => Array() [3] => Array()
)
Surprisingly, the unserialized vulgar words are showing okay! I'm not sure is it possible to serialize the emails like this:
$notify['emails'] = serialize (array($body->emails));
I faced the exact situation in the past where unserialization did not work for me, there is something not clear to me and I need to learn it. Could anyone confirm or tell me what's wrong?
N.B. The above code is from memory and may not be accurate as I currently don't have access to it.
if i am reading this correctly you are writing an array into a db
drupal_write_record('prvtmsg_notify', $notify);
should be:
drupal_write_record('prvtmsg_notify', serialize($notify));
you will most likely no longer need
$notify['emails'] = serialize($body->emails);
and can instead write:
$notify['emails'] = $body->emails;
after retrieving it from the db you can unserialize the array and iterate over it ex:
$array = unserialize(someFunctionToGetPrvtmsg_notifyFromTheDb());
//the array should be the same as the one you serialized
Related
I have a function
function getUser($linkedInID) {
$sql = "SELECT * FROM ipadapi.users WHERE linkedInID = '".$linkedInID."'";
$results = mysql_query($sql) or die("Error in User SQL query.");
return $results;
}
and this is called via
$returnedUser = getUser($linkedInID);
// Generate the array for the JSON String
$returnedMessage = array(
'status' => 'ok',
'error' => false,
'avatar' => $returnedUser['avatar'],
'userSelectedTheme' => $returnedUser['userSelectedTheme'],
'checksum' => $checksum
);
// JSONify the string and return it
$returnedJSON = json_encode($returnedMessage);
echo $returnedJSON;
However the results of $returnedUser['(field name']Althought, are always coming up NULL. avatar, userSelectedTheme are some of the fields from the dbase. I have confirmed in the database the infomation is there
I suspect I am missing a key line from my function which involves =array() somewhere and manflu is preventing me seeing it.
Any advice greatly appreicated
First of all stop using mysql_(Why shouldn't I use mysql_* functions in PHP?) is deprecated.
mysql_query from getUser function returns a resource. you must
return an array. so have a look at mysql_fetch_array or mysql_fetch_assoc functions
basically you must return mysql_fetch_array($results) assuming that is only one result comming from db. otherwise you'll have to loop through them.
Thanks to all those who answered, and extra plaudits to those who spotted the use of the depreciated mysql commands.
Had a shot of espresso and got the answer working (albeit unsafe and unsecure and..)
function getUser($linkedInID) {
$sql = "SELECT * FROM ipadapi.users WHERE linkedInID = '".$linkedInID."'";
$results = mysql_query($sql) or die("Error in User SQL query.");
$arr = array();
while($row= mysql_fetch_assoc($results)){
$arr['avatar'] = $row['avatar'];
$arr['userSelectedIndustry'] = $row['userSelectedIndustry'];
}
return $arr;
}
and the call
$returnedUser = array();
$linkedInID = filter_var($_REQUEST['linkedInID'], FILTER_SANITIZE_STRING);
$returnedUser = getUser($linkedInID);
// Generate the array for the JSON String
$returnedMessage = array(
'status' => 'ok',
'error' => false,
'avatar' => $returnedUser['avatar'],
'userLinkedInIndustry' => $userLinkedInIndustry,
'userSelectedTheme' => $returnedUser['userSelectedTheme'],
'userSelectedIndustry' => $returnedUser['userSelectedIndustry'],
'checksum' => $checksum
);
// JSONify the string and return it
$returnedJSON = json_encode($returnedMessage);
echo $returnedJSON;
many thanks for all time spent, and apologies for not just getting my head down and figuring it out
$data=array();
while($row=$result->fetch_array(MYSQLI_ASSOC))
{
data[]=$row;
}
return $row;
I am having a bit of trouble trying to explain this correctly, so please bear with me...
I need to be able to recursively select keys based on a given array. I can do this via a fairly simple foreach statement (as shown below). However, I prefer to do things via PHP's built in functions whenever possible.
$selectors = array('plants', 'fruits', 'apple');
$list = array(
'plants' => array(
'fruits' => array(
'apple' => 'sweet',
'orange' => 'sweet',
'pear' => 'tart'
)
)
);
$select = $list;
foreach ($selectors as $selector) {
if (isset($select[$selector])) {
$select = $select[$selector];
} else {
exit("Error: '$selector' not found");
}
}
echo $select;
See this code in action
My Question: Is there a PHP function to recursively select array keys? If there is not, is there a better way than in the example above?
If i understand , you are searching about :
http://php.net/recursivearrayiterator
and
http://php.net/recursiveiteratoriterator
And code something like that:
$my_itera = new RecursiveIteratorIterator(new RecursiveArrayIterator($my_array));
$my_keys = array();
foreach ($my_itera as $my_key => $value) {
for ($i = $my_itera->getDepth() - 1; $i >= 0; $i--) {
$my_key = $my_itera->getSubIterator($i)->key() . '_' . $my_key;
}
$my_keys[] = $my_key;
}
var_export($my_keys);
I Hope it works.
Good Day
I have an array containing data seperated by a comma:
array (
[0]=>Jack,140101d,10
[1]=>Jack,140101a,15
[2]=>Jack,140101n,20
[3]=>Jane,141212d,20
[4]=>Jane,141212a,25
[5]=>Jane,141212n,30
)
There is a lot of data and I would like the data to be set out as:
array(
[Jack]=>
[140101]
=>[d] =>10
=>[a] =>15
=>[n] =>20
)
My code:
foreach ($out as $datavalue) {
$dat = str_getcsv($datavalue,',');
$datevalue = substr($dat[1],2,-1);
$shiftvalue = substr($dat[1],-1);
$totalvalue = $dat[2];
$sval[$shiftvalue] = $totalvalue;
$dval[$datevalue] = $sval;
$opvalue = $dat[0];
$final[$opvalue] = $dval;
}
Now it seems the array is populated even if there is no data from the original string, so my output shows results for Jack on the other dates even though there was no data for him originally. Hope this makes sense. Could anyone point out or suggest a solution please?
As mentioned in the comments, explode is what you need. See this working here.
<?php
$input = array (
0 => 'Jack,140101d,10',
1 => 'Jack,140101a,15',
2 => 'Jack,140101n,20',
3 => 'Jane,141212d,20',
4 => 'Jane,141212a,25',
5 => 'Jane,141212n,30',
);
$result = array();
foreach ($input as $key => $value) {
$valueParts = explode(',',$value); // now valueparts is an array like ('Jack','140101d','10')
$namePart = $valueParts[0];
$idPart = substr($valueParts[1],0,-1); // we need to strip the letter from the id
$charPart = substr($valueParts[1],-1); // and the id from the letter
$nrPart = $valueParts[2]; // you could use intval() to make this an integer rather than a string if you want
// Now we fill the array
if(!array_key_exists($namePart, $result)) {
$result[$namePart] = array();
}
if(!array_key_exists($idPart, $result[$namePart])) {
$result[$namePart][$idPart] = array();
}
if(!array_key_exists($charPart, $result[$namePart][$idPart])) {
$result[$namePart][$idPart][$charPart] = $nrPart;
}
}
var_dump($result);
I have an array with structure generated like this:
$groups = array();
while ($group = mysql_fetch_array($groups_result)) {
$groups[] = array( 'id' => $group['id'], 'name' => $group['name']);
}
How can I later in the code get the name of the group by its id? For example, I would like a function like:
function get_name_by_id($id, $array);
But I'm looking for some solution which is already implemented in PHP. I know it would be easier to make arrays with array[5] = array('name' => "foo") etc where 5 in this case is id, but in my code there is a lot of arrays already created like i mentioned above and I cannot easily switch it.
$groups = array();
while ($group = mysql_fetch_assoc($groups_result)) {
$groups[$group['id']] = array( 'name' => $group['name']);
}
$name = $groups['beer']['name'];
also please not using fetch_assoc is more efficient than fetch array
function get_name_by_id($id, $data) {
foreach($data as $d) {
if ($d['id'] == $id) {
return $d['name'];
}
}
// return something else, id was not found
}
I would like to append html to an item in my array before echoing it on my page and am unsure how to go about doing it.
My data is put into an array like so:
$query = $this->db->get();
foreach ($query->result() as $row) {
$data = array(
'seo_title' => $row->seo_title,
'seo_description' => $row->seo_description,
'seo_keywords' => $row->seo_keywords,
'category' => $row->category,
'title' => $row->title,
'intro' => $row->intro,
'content' => $row->content,
'tags' => $row->tags
);
}
return $data;
I would like to perform the following on my 'tags' before returning the data to my view:
$all_tags = explode( ',' , $row->tags );
foreach ( $all_tags as $one_tag ){
echo '' . $one_tag . '';
The reason for doing this is that the tags in my database contain no html and are simply separated by commas like so news,latest,sports and I want to convert them into
sports ...
My reason for doing this here rather than when I echo the data is that I don't want to repeat myself on every page.
You could just create a function to be used everyhwere you are including tags in your output:
function formatTags($tags) {
$tmp = explode(',', $tags);
$result = "";
foreach ($tmp as $t) {
$result .= sprintf('%s',
urlencode(trim($t)), htmlentities(trim($t)));
}
return $result;
}
And whenever you do something like echo $tags; you do echo formatTags($tags); instead. View code should be separated from model code, which is why I would advise to not put HTML inside your array.
Well first of all you're overwriting $data with every run of the loop so only the final result row will be listed.
Once that's out of the way (fix with $data[] = ...), try this:
...
'tags' => preg_replace( "/(?:^|,)([^,]+)/", "$1", $row->tags);
...