PHP adding foreach to my array - php

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);
...

Related

Getting extra slashes while using JSON array in PHP

I am getting some extra slashes while making json array using PHP. My code is below.
<?php
$output=array(array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA001","subject"=>"Mathematics"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA002","subject"=>"History"),array("first_name"=>"Rama","last_name"=>"Nayidu","reg_no"=>13,"paper_code"=>"BA001","subject"=>"Geology"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA003","subject"=>"Science"));
$result = []; // Initialize result array
foreach ($output as $key => $value) {
$name = $value['first_name'] . ' ' . $value['last_name'];
// check if same name already has entry, create one if not
if (!array_key_exists($name, $result)) {
$result[$name] = array(
'reg_no' => $value['reg_no'],
'name' => $name,
'paper1' => '',
'paper2' => '',
'paper3' => '',
'paper4' => ''
);
}
// count array elements with value, then set paper number and value
$paper = 'paper' . (count(array_filter($result[$name])) - 1);
$result[$name][$paper] = $value['paper_code'].'/'.$value['subject'];
}
$result = array_values($result); // reindex result array
echo json_encode($result);exit;
?>
Here the json output is given below.
[{"reg_no":12,"name":"robin sahoo","paper1":"BA001\/Mathematics","paper2":"BA002\/History","paper3":"BA003\/Science","paper4":""},{"reg_no":13,"name":"Rama Nayidu","paper1":"BA001\/Geology","paper2":"","paper3":"","paper4":""}]
Here my problem is I am adding $value['paper_code'].'/'.$value['subject']; and in output I am getting "BA001\/Mathematics". Here One extra slash(\) is added which I need to remove.
You can add JSON_UNESCAPED_SLASHES as the second parameter. LIke:
$result = array_values($result); // reindex result array
echo json_encode($result,JSON_UNESCAPED_SLASHES);exit;
This will result to:
[{"reg_no":12,"name":"robin sahoo","paper1":"BA001/Mathematics","paper2":"BA002/History","paper3":"BA003/Science","paper4":""},{"reg_no":13,"name":"Rama Nayidu","paper1":"BA001/Geology","paper2":"","paper3":"","paper4":""}]
Doc: json_encode()

php json multidimensional array syntax

I have a problem with the JSON I'm creating in PHP; I create the array in a while loop from an sql query. $featuresCSV is a comma-separated string like "1,3,4". In the JSON I need it to end up like feature-1: 1,feature-2: 1,feature-3: 1 The 1 represents true for my checkbox in my front-end program.
while ($stmt2->fetch()) {
$features = array();
$featuresTmp = explode(',', $featuresCSV, -1);
foreach ($featuresTmp as &$featureItem) {
$features[] = array("feature-" . $featureItem => 1);
}
$items[] = array('price' => $price, 'image' => $image, 'features' => $features);
}
...
json_encode($output);
The JSON ends up looking like this:
{"price":8900,
"image":"4d3f22fe-9f1a-4a7e-a564-993c821b2279.jpg",
"features":[{"feature-1":1},{"feature-2":1}]}
but I need it to look like this:
{"price":8900,
"image":"4d3f22fe-9f1a-4a7e-a564-993c821b2279.jpg",
"features":[{"feature-1":1,"feature-2":1}]}
Notice how feature-1 and feature-2 aren't separated by brackets in the second.
You need to assign the elements at "feature-1" and "feature-2".
foreach ($featuresTmp as &$featureItem) {
$features["feature-" . $featureItem] = 1;
}
The syntax $feature[] = ... is for appending to the end of an array.
Here ya go
while ($stmt2->fetch()) {
$features = array();
$featuresTmp = explode(',', $featuresCSV, -1);
foreach ($featuresTmp as &$featureItem) {
$features["feature-$featureItem"] = 1;
}
$items[] = array('price' => $price, 'image' => $image, 'features' => $features);
}
...
json_encode($output);

Using an array as function parameter php

I have an array that I would like to pass to a function as a parameter. These array values will be used to pull values out of another array and display them.
My Function:
function showTreadmills($listbrands) {
global $treadmills;
foreach( $treadmills as $brand=>&$features ) {
if ($brand == $listbrands) {
return '<p>'.$features["description"].'</p>';
}
}
}
Treadmills Array:
$treadmills = [
'bowflexseries3' => [
'description' => 'Bowflex Series 3',
'image' => '/images/bowflex-series-3-150x150.jpg',
'url' => '/treadmills/bowflex/series-3',
],
'solef85' => [
'description' => 'Sole F85',
'image' => '/images/sole-f85-150x150.jpg',
'url' => '/treadmills/sole/f-85',
],
'endurancet10hrc' => [
'description' => 'Endurance T10HRC',
'image' => '/images/endurance-t10hrc-150x150.jpg',
'url' => '/treadmills/endurance/t10hrc',
]
];
Values that I'm trying to pull out of array in my function:
<?php echo showTreadmills('bowflexseries3','solef85'); ?>
This only returns the first Description from the array, which is Bowflex Series 3. I'm trying to figure out how to get it to pull the description for bowflexseries3 and solef85. I'm sure it's a dumb oversight. Thanks in advance!
You're not passing an array to the function, you're passing two strings. You need to call array() to wrap an array around them:
echo showTreadmills(array('bowflexseries3','solef85'));
Then you need to change showTreadmills. You can't use == to compare a string to an array. It looks like you want to test whether the string is in the array, so it should be:
if (in_array($brand, $listbrands))
Or instead of looping through $treadmills and testing whether it's equal to one of $listbands, you could loop through $listbrands:
$result = '';
foreach ($listbrands as $brand) {
if (isset($treadmills[$brand])) {
$result .= '<p>'.$treadmills[$brand]["description"].'</p>';
}
}
return $result;
This is better, since it loops through the smaller array. And in_array() has to do a search, while accessing an associative array is just a hash lookup.
Notice that you need to concatenate the results into a string during the loop. If you use return in the loop, you'll only return the first brand found.
The problem is that you are returning on your first match:
if ($brand == $listbrands) {
return '<p>'.$features["description"].'</p>';
}
You will need to store all your matches so the entire loop can finish and then send back everything that matched.
$matches = '';
foreach( $treadmills as $brand=>&$features ) {
if ($brand == $listbrands) {
$matches .= '<p>'.$features["description"].'</p>';
}
}
return $matches;
function showTreadmills($listbrands) {
global $treadmills;
$out = '';
foreach( $treadmills as $brand=>&$features ) {
if ($brand == $listbrands) {
$out .= '<p>'.$features["description"].'</p>';
}
}
return $out;
}

Drupal PHP serialize and unserialize

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

If array value begins with

I have an array of values.
My crawler scans the web page and inserts all the links, the links' titles and description is a multidimensional array.
But now I have a new array and I only want the links, descriptions and titles etc. if they begin with any value in the array ($bbc_values)
But I don't really know how to do this. I have have gotten pretty far in terms of the actual code but can anyone give me any ideas a) why my code isn't working b) suggestions for my problem?
$bbc_values = array('http://www.bbc.co.uk/news/health-', 'http://www.bbc.co.uk/news/politics-', 'http://www.bbc.co.uk/news/uk-', 'http://www.bbc.co.uk/news/technology-', 'http://www.bbc.co.uk/news/england-', 'http://www.bbc.co.uk/news/northern_ireland-', 'http://www.bbc.co.uk/news/scotland-', 'http://www.bbc.co.uk/news/wales-', 'http://www.bbc.co.uk/news/business-', 'http://www.bbc.co.uk/news/education-', 'http://www.bbc.co.uk/news/science_and_enviroment-', 'http://www.bbc.co.uk/news/entertainment_and_arts-', 'http://edition.cnn.com/');
foreach ($links as $link) {
$output = array(
"title" => Titles($link), //dont know what Titles is, variable or string?
"description" => getMetas($link),
"keywords" => getKeywords($link),
"link" => $link
);
if (empty($output["description"])) {
$output["description"] = getWord($link);
}
}
$data = implode( " , ", $output['link']);
foreach ($output as $new_array) {
if (in_array($output, $bbc_values)) {
$news_stories[] = $new_array;
}
var_dump($news_stories);
}
Okay, I don't completely understand the code here.
But I think $output array should be declared outside the first foreach loop and each array should be appended to it?
Because from the code you're writing, only the details of last $link will be stored inside the $output
Also, what is $data here? what are you using it for?
Turn $bbc_values into a regex:
$bbc_re = '/^('.implode('|', array_map('quotemeta', $bbc_values)).')/';
Then use this regex to filter the links.
foreach ($links as $link) {
if (preg_match($bbc_re, $link)) {
/* Do stuff with $link */
}
}
I assume you what you want is to have an array with links that starts with of the links in the bbc_values and additionally a string $data with a comma separated list of all links. Try something this :
<?php
$bbc_values = array('http://www.bbc.co.uk/news/health-', 'http://www.bbc.co.uk/news/politics-', 'http://www.bbc.co.uk/news/uk-', 'http://www.bbc.co.uk/news/technology-', 'http://www.bbc.co.uk/news/england-', 'http://www.bbc.co.uk/news/northern_ireland-', 'http://www.bbc.co.uk/news/scotland-', 'http://www.bbc.co.uk/news/wales-', 'http://www.bbc.co.uk/news/business-', 'http://www.bbc.co.uk/news/education-', 'http://www.bbc.co.uk/news/science_and_enviroment-', 'http://www.bbc.co.uk/news/entertainment_and_arts-', 'http://edition.cnn.com/');
$news_stories = array();
$all_links = array();
$news_links = array();
foreach ($links as $link) {
$item = array(
"title" => Titles($link),
"description" => getMetas($link),
"keywords" => getKeywords($link),
"link" => $link
);
if (empty($item["description"])) {
$item["description"] = getWord($link);
}
foreach($bbc_values as $bbc_value) {
// note the '===' . this is important
if(strpos($item['link'], $bbc_value) === 0) {
$news_stories []= $item;
$news_links []=$item['link'];
break;
}
}
$all_links[] = $item['link'];
}
$data_all_links = implode(' , ', $all_links);
$data_news_links = implode(' , ', $news_links);
var_dump($news_stories);

Categories