How to add html to an array in php? - php

I am trying to add some html code before each tag printed as an array element.
My code:
$term_links = array();
foreach ($vars['node']->taxonomy as $term)
{
$term_links[] = l($term->name, 'taxonomy/term/' . $term->tid,
array(
'attributes' => array(
'title' => $term->description
)));
}
$vars['node_terms'] = implode(', ', $term_links);
At the moment the tags are printed seperated by a comma. I would like to add a small image before each tag element using img src="tag.png" How can I do this?
EDIT - My current Code, still not working.
if (module_exists('taxonomy')) {
$img = 'some html';
$text = $img . $term->name;
$path = 'taxonomy/term/' . $term->tid;
$term_links = array();
foreach ($vars['node']->taxonomy as $term) {
$term_links[] = l($text, $path, array(
'html' => TRUE,
'attributes' => array(
'title' => $term->description
)));
}
$vars['node_terms'] = implode(', ', $term_links);
}
}

Dupal's l() function has an option "html" you can set it to TRUE and use IMG + TITLE as a title.
Here is the example:
$img = '<img src="..." />';
$text = $img . $term->name;
$path = 'taxonomy/term/' . $term->tid;
$term_links[] = l($text, $path, array(
'html' => TRUE,
'attributes' => array(
'title' => $term->description
)
));

Related

Display product price when searching

I purchased a search module that displays a popup and would like to add the price of the product I searched for in it, I found the file that I should make the changes, but what should I add to display the product price
This is the responsible function for displaying the product characteristics
protected function _prepareProducts()
{
$isEnabledImage = (bool) Mage::getStoreConfig(self::ENABLE_IMAGE_CONFIG);
$imageHeight = (int) Mage::getStoreConfig(self::IMAGE_HEIGHT_CONFIG);
$imageWidth = (int) Mage::getStoreConfig(self::IMAGE_WIDTH_CONFIG);
$isEnabledDescription = (bool) Mage::getStoreConfig(self::ENABLE_DESCRIPTION_CONFIG);
$lengthDescription = (int) Mage::getStoreConfig(self::DESCRIPTION_LENGTH_CONFIG);
$collection = $this->_getAlternativeProductCollection();
// $this->_prepareQueryPopularity($collection->getSize());
$toolbar = $this->getToolbarBlock();
$toolbar->setCollection($collection);
$size = (int) Mage::getStoreConfig(self::RESULT_SIZE_CONFIG);
$collection->setPageSize($size);
// $collection->getSelect()->limit($size);
$sortOrder = Mage::getStoreConfig(self::SORT_ORDER_PRODUCT);
if (0 < count($collection)) {
$this->_suggestions[$sortOrder][] = array('html' =>
'<p class="headercategorysearch">' . $this->__("") . '</p>'
);
}
if ($isEnabledImage) {
$helper = Mage::helper('catalog/image');
}
foreach ($collection as $_row) {
$_product = Mage::getModel('catalog/product')
->setStoreId($this->getStoreId())
->load($_row->getId());
$_image = $_srcset = $_description = '';
if ($isEnabledImage) {
$_image = (string) $helper->init($_product, 'thumbnail')->resize($imageWidth, $imageHeight);
$_srcset = (string) $helper->init($_product, 'thumbnail')->resize($imageWidth * 2, $imageHeight * 2);
$_srcset .= ' 2x';
}
if ($isEnabledDescription) {
$_description = strip_tags($this->_trim(
$_product->getShortDescription(),
$lengthDescription
));
}
// $store = Mage::app()->getStore();
// $path = Mage::getResourceModel('core/url_rewrite')
// ->getRequestPathByIdPath('product/' . $_product->getId(), $store);
// // $url = $store->getBaseUrl($store::URL_TYPE_WEB) . $path;
// $url = rtrim(Mage::getUrl($path, array('_store' => $store->getStoreId())), '/');
$url = $_product->getProductUrl();
$this->_suggestions[$sortOrder][] = array(
'name' => $_product->getName(),
'url' => $url,
'image' => $_image,
'srcset' => $_srcset,
'description' => $_description,
);
}
}
Simply add this line
'price' => $_product->getPrice() in suggestions array
$this->_suggestions[$sortOrder][] = array(
'name' => $_product->getName(),
'price' => $_product->getPrice(),
'url' => $url,
'image' => $_image,
'srcset' => $_srcset,
'description' => $_description,
);
you may use
$_product->getFinalPrice()
inside this _suggestions property, but i guess there is also a template or a bit of js responsible for output of all this.

PHP if/else based on parameter being true

This is part of the PHP that is outputting HTML from a function I'm working on. I'm getting stuck on the if/else state where I need to check if a parameter is set to true or false.
If it's set to true, I have HTML I want to output, if it's false, nothing needs to happen.
<?php
/**
*
*
* #param array $settings
*
* #return string
*/
function PCStandardTextBlock( $settings = array() ) {
//---- Get Settings ----
//The functions default settings will be merged with what's passed in.
$settingsDefault = array(
'small_heading' => '',
'large_heading' => '',
'text' => '',
'text_mode' => 'basic', //or advanced
'big_first_p' => false,
'link_url' => '',
'link_text' => '',
'link_new_tab' => false,
'link_style' => 'action_link', //or button
'photo' => '', //cloudinary id
'image_alt_text' => '',
'crop_gravity' => 'face',
'icon' => '', //icn-class
'color_scheme' => 'white', //or accent1, accent2, accent4
'container_id' => '',
'container_class' => '',
'special_feature' => 'camplife_links', //or link_modal, hidden_content
'modal_id' => '',
'hidden_content_location' => 'another_block', //or in_this_block (see day-camps.php)
'hidden_text' => '',
'hidden_content_id' => '',
);
$settings = array_merge($settingsDefault, $settings);
//---- Set Variables ----
//These will allow the markup buildup to be as clean as possible.
$has_photo = strlen($settings['photo']) > 0;
$has_icon = strlen($settings['icon']) > 0;
$has_small_heading = strlen($settings['small_heading']) > 0;
$has_image_alt_text = strlen($settings['image_alt_text']) > 0;
//Note to Sal: If text mode is basic, wrap it in a <p> tag, if advanced, don't.
//If container_id is set, prepare the attribute
$has_container_id = strlen($settings['container_id']) > 0;
$possible_container_id_attribute = ($has_container_id) ? " id='{$settings['container_id']}'" : "";
//Handle the color scheme setting
switch( $settings['color_scheme'] ) {
case 'accent1': // blue
$gcol_color_class = 'bg-color-accent1-C';
$small_heading_color_class = 'color-white';
$icon_color_class = 'color-white';
break;
case 'accent2': // green
$gcol_color_class = 'bg-color-accent2-C';
$small_heading_color_class = 'color-white';
$icon_color_class = 'color-white';
break;
case 'accent4': // yellow
$gcol_color_class = 'bg-color-accent4-D';
$small_heading_color_class = 'color-accent1-9';
$icon_color_class = 'color-accent1-9';
break;
default; //white
$gcol_color_class = ''; // empty
$small_heading_color_class = 'color-base-A';
$icon_color_class = 'color-accent1-9';
}
// Handle the special feature setting
switch( $settings['special_feature']) {
case 'camplife_links':
$special_feature_display = '<div class="spacer"></div>
<div class="grid">
<div class="gcol">
<a target="_blank" href="https://itunes.apple.com/us/app/pine-cove-camplife/id991165025?mt=8&ign-mpt=uo%3D4">
<img class="width-100" src="/images/logos/badges/app-store-badge.png" alt="Download on the App Store" />
</a>
</div>
<div class="gcol">
<a target="_blank" href="https://play.google.com/store/apps/details?id=com.pinecove.camplife">
<img class="width-100" src="/images/logos/badges/google-play-badge.png" alt="Get it on Google Play" />
</a>
</div>
</div>';
break;
default; // don't show anything
$special_feature_display = ''; // Empty
}
$has_special_feature = strlen( $settings['special_feature'] ) > 0;
// Settings to call PCResponsiveImage with output set to false to save the results to a variable for inclusion in the output
$responsive_image_settings = array(
'cloudinary_ID' => $settings['photo'],
'aspect_ratios' => '1x1',
'crop_gravity' => $settings['crop_gravity'],
'screen_portion' => 'partial',
'style_profile' => 'style4',
'output' => false,
);
// If image alt text has been set, us it, otherwise don't set anything so responsive image can do it's thing (it sets the alt text to the filename).
if ( $has_image_alt_text ) {
$responsive_image_settings['alt_text'] = $settings['image_alt_text'];
}
//Save PCResponsiveImage markup to a variable
$responsive_image_html = PCResponsiveImage( $responsive_image_settings );
//---- Build Output ----
//Line by line, concatenating strings with new line and tab characters.
$output = "\n<!-- Standard Text Block -->";
$output .= "\n<div class='gcol-md-1-2 {$gcol_color_class} {$settings['container_class']}'{$possible_container_id_attribute}>";
$output .= "\n\t<div class='padbox-standard-content'>";
if( $has_photo ) {
$output .= "\n\t<div class='small-heading-image'>";
$output .= "\n\t\t{$responsive_image_html}";
$output .= "\n\t</div>";
} elseif( $has_icon ) {
$output .= "<span class='icn {$settings['icon']} $icon_color_class width-90'></span>";
}
if( $has_small_heading ) {
$output .= "\n\t<h1 class='small-heading $small_heading_color_class'>{$settings['small_heading']}</h1>";
}
$output .= "\n\t<h2 class='heading-extended'>{$settings['large_heading']}</h2>";
if ( $settings['text_mode'] == 'basic' ) {
$output .= "\n\t\t\t\t<p>{$settings['text']}</p>"; // basic version
} elseif ( $settings['big_first_p'] === true ) {
$output .= "\n\t\t\t\t<p class='big-p'>{$settings['text']}</p>";
} else {
$output .= "\n\t\t\t\t{$settings['text']}"; // advanced text mode; not big-p
}
if( $has_special_feature ) {
$output .= "\n\t\t\t$special_feature_display";
}
$output .= "\n\t</div><!-- END padbox-standard-content -->";
$output .= "\n</div><!-- END gcol-md-1-2 -->";
//---- Return Output ----
return $output;
}
This is the function on the page where it calls the function (I've left off some parameters in the function call above to save space):
<?php echo PCStandardTextBlock(
array(
'small_heading' => 'Small Heading',
'large_heading' => 'Large Heading',
'text' => 'This is example text that is just basic text. If this was advanced text, then it would be multiple paragraphs.',
'text_mode' => 'basic',
'big_first_p' => true,
'photo' => '',
'image_alt_text' => '',
'icon' => '',
'color_scheme' => 'white',
'special_feature' => '',
'container_id' => '',
'container_class' => '',
)
); ?>
It looks like you were checking a non-existent array key: $settings['big_first_p']. Here it is corrected:
$settingsDefault = array(
'big_first_p' => false,
);
if ( $settingsDefault['text_mode'] == 'basic' ) {
$output .= "\n\t\t\t\t<p>{$settings['text']}</p>"; // basic version
} elseif ( $settingsDefault['big_first_p'] === true ) {
$output .= "\n\t\t\t\t<p class='big-p'>{$settings['text']}</p>";
} else {
$output .= "\n\t\t\t\t{$settings['text']}";
}
Update:
So, you are passing in 'text_mode' => 'basic',, which is why the basic version is getting appended to $output in your if/elseif/else statement. Your code is functioning correctly.
If you want the big-p class one to be chosen, you need to place that block first in your if/elseif/else clause, or change the text_mode value you are passing into the function initially to something other than 'basic'.

Use replace string to change image size on PHP feed

I want to create a feed for a several pinterest boards. Before I get down too deep, I see the images, but they are small.
Before, using yahoo pipes I was able to modify the source and change 236x with 736x in the image URL and recreated the feed. But now that the service is about to shut down, I want to find a different alternative. Tried several services, but none seem to do the replacement as I want.
I know the image is in the description, but can't figure out how to use str_replace to accomplish this.
Hope you can share some ideas, thank you.
I have this so far:
<?php
$rss = new DOMDocument();
$feed = array();
$urlArray = array(array('name' => 'Otaku', 'url' => 'https://www.pinterest.com/anizeen/otaku.rss'),
array('name' => 'How To', 'url' => 'https://www.pinterest.com/anizeen/how-to-draw-anime-manga.rss'),
array('name' => 'Upcoming', 'url' => 'https://www.pinterest.com/anizeen/upcoming-anime-attractions.rss'),
array('name' => 'Manga', 'url' => 'https://www.pinterest.com/anizeen/manga.rss')
);
foreach ($urlArray as $url) {
$rss->load($url['url']);
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'site' => $url['name'],
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
);
array_push($feed, $item);
}
}
usort($feed, function($a, $b) {
return strtotime($b['date']) - strtotime($a['date']);
});
$limit = 3;
echo '<ul>';
for ($x = 0; $x < $limit; $x++) {
$site = $feed[$x]['site'];
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
$link = $feed[$x]['link'];
$desc = str_replace('/236x/', '/736x/', $desc);
$description = $feed[$x]['desc'];
$date = date('l F d, Y', strtotime($feed[$x]['date']));
echo '<p><strong>'.$title.'</strong><br />';
echo '<small><em>'.$date.'</em></small></p>';
echo '<p>'.$description.'</p>';
}
?>

Yii cgridview add custom html attribute to buttons from data not working

I tried to add custom html attribute to cgridview buttons from dataProvider , Im using bootstrap yii bootstrap bootstrap.widgets.TbButtonColumn
I tried
'pbs_id'=>'{$data->pbs_id}',
and
'pbs_id'=>'{$data["psp_id"]}',
but it return it as string
$this->widget('bootstrap.widgets.TbGridView', array(
'type'=>'striped bordered condensed',
'dataProvider'=>$db_slabs_data,
'template'=>"{items}",
'columns'=>array(
array('name'=> 'pbs_id', 'header'=>'Slab Id'),
array('name'=> 'pbs_name', 'header'=>'Slab Name'),
array(
'htmlOptions' => array('nowrap'=>'nowrap'),
'class'=>'bootstrap.widgets.TbButtonColumn',
'template'=>"{update}",
'updateButtonUrl'=>'Yii::app()->createUrl("", array("pbs_id"=>$data["pbs_id"]))',
'buttons'=>array
(
'update' => array
(
'label'=> Yii::t('common', 'LBL_UPDATE'),
'icon'=>'icon-pencil',
'url'=>'Yii::app()->createUrl("", array("pbs_id"=>$data["pbs_id"]))',
'options'=>array(
'pbs_id'=>'{$data["psp_id"]}',
),
),
),
),
),
));
ad the result is :
<i class="icon-pencil"></i>
how I can do that.
Thanks
I solved my problem by:
inside this file /protected/extensions/bootstrap/widgets/TbButtonColumn.php there are a method renderButton()
I override this method to to render additional html attribute for buttons:
protected function renderButton($id, $button, $row, $data) {
if (isset($button['visible']) && !$this->evaluateExpression($button['visible'], array('row' => $row, 'data' => $data)))
return;
$label = isset($button['label']) ? $button['label'] : $id;
$url = isset($button['url']) ? $this->evaluateExpression($button['url'], array('data' => $data, 'row' => $row)) : '#';
$options = isset($button['options']) ? $button['options'] : array();
/* added to render additional html attribute */
if (isset($button['options']) AND !(empty($button['options']))) {
foreach ($button['options'] as $key => $value) {
if (preg_match('#\$(data|row)#', $value)) {
$options["$key"] = $this->evaluateExpression($button['options'][$key], array('data' => $data, 'row' => $row));
} else {
$options["$key"] = $value;
}
}
}
/* end */
if (!isset($options['title']))
$options['title'] = $label;
if (!isset($options['rel']))
$options['rel'] = 'tooltip';
if (isset($button['icon'])) {
if (strpos($button['icon'], 'icon') === false)
$button['icon'] = 'icon-' . implode(' icon-', explode(' ', $button['icon']));
echo CHtml::link('<i class="' . $button['icon'] . '"></i>', $url, $options);
}
else if (isset($button['imageUrl']) && is_string($button['imageUrl']))
echo CHtml::link(CHtml::image($button['imageUrl'], $label), $url, $options);
else
echo CHtml::link($label, $url, $options);
}
and inside the grid
'buttons'=>array
(
'update' => array
(
'label'=> Yii::t('common', 'LBL_UPDATE'),
'icon'=>'icon-pencil',
'url'=>'Yii::app()->createUrl("", array("pbs_id"=>$data["pbs_id"]))',
'options'=>array(
'id'=>'$data["id"]',
'new_attribute'=> '$data["your_key"]',
),
),
),
Well, you simply cannot do this like this, options values will not be evaluated as PHP expression : http://www.yiiframework.com/doc/api/1.1/CButtonColumn#buttons-detail
You should extend bootstrap.widgets.TbButtonColumn to handle this, e.g. :
Create a new file MyTbButtonColumn.php in protected/widgets (or else) :
Yii::import('bootstrap.widgets.TbButtonColumn');
class MyTbButtonColumn extends TbButtonColumn
{
protected function renderButton($id, $button, $row, $data)
{
if (isset($button['options']) && is_array($button['options']))
{
foreach ($button['options'] as &$v)
{
// evaluate ?
if (preg_match('#\$(data|row)#', $v))
$v = $this->evaluateExpression($v, array('data'=>$data, 'row'=>$row));
}
}
parent::renderButton($id, $button, $row, $data);
}
}
And modify your view :
$this->widget('application.widgets.MyTbButtonColumn', array(...));
PS: You could also use javascript to add these attributes.

Read nested array dynamicly in php

I need to read nested arrays without knowing how the array will look.
For example;
$data = array(
'Data1_lvl1' => array(
'Data1_lvl2' => "value",
'Data2_lvl2' => array(
'Data1_lvl3' => "value"
)
),
'Data2_lvl1' => 'value'
);
Needs to be formatted to strings like:
Data1_lvl1/Data1_lvl2/
Data1_lvl1/Data2_lvl2/Data1_lvl3/
Data2_lvl1/
But the array can be of any size with any number of nested arrays inside it.
$data = array(
'Data1_lvl1' => array(
'Data1_lvl2' => "value",
'Data2_lvl2' => array(
'Data1_lvl3' => "value"
)
),
'Data2_lvl1' => 'value'
);
function printArray($array)
{
foreach ($array as $key=>$value)
{
echo $key.'/';
if (is_array($value))
{
printArray($value);
} else {
echo '<br>';
}
}
}
printArray($data);
If you want to output only the name of array elements then this recursive function will do the trick.
Your data:
$data = array(
'Data1_lvl1' => array(
'Data1_lvl2' => "value",
'Data2_lvl2' => array(
'Data1_lvl3' => "value"
)
),
'Data2_lvl1' => 'value'
);
Function:
function array2str($array, $str) {
foreach($array as $key => $val) {
if (is_array($val) ) {
$str .= $key . '/';
array2str($val, $str);
}
}
echo $str.'<br />';
return $str;
}
array2str($data);
As you can see the script does ECHO in itself with <br /> to break the line when viewing results in a browser.
One way would to walk recursively through array with function similar to this:
<?php
function f($d, $str = '') {
foreach ($d as $key => $val) {
if (is_array($val)) f($val, $str . '/' . $key); // If this element is array parse next level
else print_r($str . '/' . $key . '/'); // Output current string or do what you need to do with it..
}
}
$data = array(
'Data1_lvl1' => array(
'Data1_lvl2' => "value",
'Data2_lvl2' => array(
'Data1_lvl3' => "value"
)
),
'Data2_lvl1' => 'value'
);
f($data);
with that function:
<?php
function print_tree ($data, $prefix = '', &$index = 1) {
foreach($data as $key => $datum) {
echo $index++ . '. ' . ($new_prefix = $prefix . $key . '/') . PHP_EOL;
if (is_array($datum)) {
print_tree ($datum, $new_prefix, $index);
}
}
}
I get
Data1_lvl1/
Data1_lvl1/Data1_lvl2/
Data1_lvl1/Data2_lvl2/
Data1_lvl1/Data2_lvl2/Data1_lvl3/
Data2_lvl1/

Categories