I'm thinking there is an easier way to write this code, but not sure on what approach to take. Basically, I want to check if each variable exists, and if so - add the appropriate markup to the page.
Any suggestions would be great.
<?php
$words = get_field('words');
$photography = get_field('photography');
$architect = get_field('architect');
?>
<div class="panel">
<?php if( $words ): ?>
<div>
<p><span>Words</span><span><?php echo $words;?></span></p>
</div>
<?php endif ;?>
<?php if( $photography ): ?>
<div>
<p><span>Photography</span><span><?php echo $photography;?></span></p>
</div>
<?php endif; ?>
<?php if( $architect ): ?>
<div>
<p><span>Architect</span><span><?php echo $architect;?></span></p>
</div>
<?php endif; ?>
</div>
You can use array & loop -
<?php
$fields = array();
$fields['words'] = get_field('words');
$fields['photography'] = get_field('photography');
$fields['architect'] = get_field('architect');
?>
<div class="panel">
<?php foreach($fields as $key => $value):
if($value)
?>
<div>
<p><span><?php echo ucwords($key);?></span><span><?php echo $value;?></span></p>
</div>
<?php
endif;
endforeach;?>
</div>
Create a field array with their appropriate label if you want to have your own labels.
<div class="panel">
<?php
$fields = array (
'words' => 'Words',
'photography' => 'Photography',
'architect' => 'Architect'
);
foreach ( $fields as $field => $label ) {
$value = get_field ( $field );
if (!empty($value)) {
echo '<div>
<p><span>' . $label . '</span><span>' . $value . '</span></p>
</div>';
}
}
?>
</div>
<?php
$required_fields = array("words","photography","architect");
$data = array();
foreach($required_fields as $field)
{
$data[$field] = get_field($field);
}
?>
<div class="panel">
<?php foreach($data as $data_field=>$data_value):
if($data_value)
?>
<div>
<p><span><?=$data_field?></span><span><?=$data_value?></span></p>
</div>
<?php
endif;
endforeach ;?>
</div>
You can create a function like this and then iterate the data that it returns to output your content
<?php
//define a function to fetch data in specific fields
function fetch_data($keys=array()){
$data = array();
foreach($keys as $key){
$val = get_field($key);
if(!empty($val)){
$data[$key] = $val;
}
}
return $data;
}
//now you can easily add or change your fields
$data = fetch_data(array('words','photography','architect'));
?>
<div class="panel">
<?php
foreach($data as $field){
if(isset($data[$field])){
$val = $data[$field];
?>
<div>
<p><span><?php echo ucfirst($field); ?></span><span><?php echo $val; ?></span></p>
</div>
<?php
}
}
?>
Related
I am trying to get a sum in my variable session basket (it is a multiple array), I want to sum the elements that represent the cost of product.
Page where I add elements into the basket
<?php
session_start();
include('link.php');
if(!isset($_SESSION['basket'])){
$_SESSION['basket']=[];
}
// $id_permit=$_POST['id_fp'];
// $chosen_date=$_POST['date_permit'];
$_SESSION['little_basket']= array (
'itemIdPermit'=> "'".$_POST["id_fp"]."'",
'itemChosenDate'=> "'".$_POST["date_permit"]."'",
'itemFinalPrice'=> "'".$_POST["final_price"]."'",
'itemFinalPriceNotDiscount'=>"'".$_POST["price_not_discount"]."'"
);
// $_SESSION['basket'][] = $_SESSION['little_basket'];
array_push($_SESSION['basket'], $_SESSION['little_basket']);
print_r($_SESSION['basket']);
// $_SESSION['basket']=[];
// echo $_SESSION['basket'];
// header('location:index.php?area=fishing_permit');
?>
Page where I show the contents of the basket
<?php
// session_start();
// include('link.php');
// include('add_basket.php');
// $ids = '';
/* foreach($_SESSION['basket'] as $id){
$ids = $ids . $id . ",";
};*/
$lista_de_items_no_carrinho = $_SESSION['basket'];
?>
<ul id="list_product">
<?php
$basketLength=count($lista_de_items_no_carrinho);
for($i=0;$i< $basketLength;$i++){
$sqlListChosenPermits = "select * from type_of_permits
where id_type_of_permit =".$lista_de_items_no_carrinho[$i]['itemIdPermit'];
$outcomeListChosenPermits = $link->query($sqlListChosenPermits);
$line = mysqli_fetch_assoc($outcomeListChosenPermits);
?>
<li>
<div class="box_info"><h4><?php echo utf8_encode($line['type']); ?></h4><br>Validity: <?php echo utf8_encode($line['validity']);?> - Price: €<?php echo utf8_encode($line['price_eur']); ?> </div>
<div class="map">Map info</div>
<div class="rules">Rules</div>
<div class="permit_facsimile">Permit facsimile</div>
<div class="chosen_date"><?php echo trim ($lista_de_items_no_carrinho[$i]['itemChosenDate'], "'") ;?></div>
<div class="price">Euro <?php
$var= trim ($lista_de_items_no_carrinho[$i]['itemFinalPrice'],"'");
if (!empty($var) ){
echo ($var);
} else {
echo trim($lista_de_items_no_carrinho[$i]['itemFinalPriceNotDiscount'],"'");
} ?></div>
<div class="add_basket"><i class="fa fa-shopping-cart"></i>Remove from the Basket</div>
<input type="hidden" name="last_price" id="last_price" value="<?php
if (!empty($lista_de_items_no_carrinho[$i]['itemFinalPrice'])) {
echo trim ($lista_de_items_no_carrinho[$i]['itemFinalPrice'],"'");
} else {
echo trim($lista_de_items_no_carrinho[$i]['itemFinalPriceNotDiscount'],"'");
} ?>">
</li>
<?php
}
?>
</ul>
<p>Total price:<span class="total_price"><?php
$lista_de_items_no_carrinho = $_SESSION['basket'];
$listaPrice=$lista_de_items_no_carrinho[$i]['itemFinalPriceNotDiscount'];
$basketLength=count($listaPrice);
$sum=0;
for($k= 0; $k < $basketLength; $k++){
$sum += ($basketLength[$k]);
echo ($sum);
}?>
</span></p>
<div class="buying"><button type="submit"><i class="fa fa-shopping-cart"></i>Conclude the purchase</button></div>
</div>
I would like to sum the numerics value of 'ItemFinalPrice' and 'ItemFinalPriceNotDiscount'.
Thanks in advance.
Fanjo
You should take a look at array_column and array_sum:
$finalPriceSum = array_sum(array_column($basket, 'itemFinalPrice'));
$finalPriceNoDiscountSum = array_sum(array_column($basket, 'itemFinalPriceNotDiscount'));
I have this loop that sorts a set of results alphabetically and shows a <span> with the current letter, but I can't find a way to wrap each subset within a div.
<?php
$previousLetter = null;
foreach($allBrands as $brand) {
$firstLetter = strtolower($brand->name[0]);
if ( $previousLetter != $firstLetter ) {
echo '<span class="designer-first-letter">'. $firstLetter .'</span>';
$previousLetter = $firstLetter;
}
echo '<p>'.$brand->name.'</p>';
}
I would like something like this
<div>
<span>A</span>
<p>Aword</p>
<p>Aword2</p>
<p>Aword3</p>
<p>...</p>
</div>
<div>
<span>B</span>
<p>Bword</p>
<p>Bword2</p>
<p>Bword3</p>
<p>...</p>
</div>
<div>
<span>C</span>
<p>Cword</p>
<p>Cword2</p>
<p>Cword3</p>
<p>...</p>
</div>
...
Right now what I get is
<span>A</span>
<p>Aword</p>
<p>Aword2</p>
<p>Aword3</p>
<p>...</p>
<span>B</span>
<p>Bword</p>
<p>Bword2</p>
<p>Bword3</p>
<p>...</p>
<span>C</span>
<p>Cword</p>
<p>Cword2</p>
<p>Cword3</p>
<p>...</p>
...
What about pre-grouping the brands before you loop through
$brands = Array("Aword", "Aword2", "Aword3", "BWord", "Bword2");
$groups = Array();
foreach($brands as $brand) {
$startsWith = strtolower($brand[0]);
if( array_key_exists($startsWith, $groups))
array_push($groups[$startsWith], $brand);
else
{
$groups[$startsWith] = Array($brand);
}
}
ksort($groups);
foreach($groups as $key => $value ) {
?>
<div>
<span><?php echo strtoupper($key) ?></span>
<?php foreach($value as $brand) { ?>
<p><?php echo $brand?></p>
<?php } ?>
</div>
<?php
}
And, ksort to make them alphabetical
I have to input several strings into table in db. Its tabular input yii. Cannot understand, how to do it this way, if i have such controller:
public function actionCreate()
{
$model1=new Section;
$model2=new SectionI18n;
if(isset($_POST['SectionI18n'])){
foreach ($model2 as $i => $m1) {
foreach($_POST['SectionI18n'] as $i => $m1)
{
$m1=new SectionI18n;
$m1->attributes=$_POST['SectionI18n'][$i];
$my[]=$m1->attributes;
}
}
and some layout:
<?php foreach ($model2 as $i=>$m1):?>
<?php ?>
<div class="row">
<?php echo $form->labelEx($model2,'Название'); ?>
<?php echo $form->textField($model2,'[$i]title',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($model2,'title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model2,'Описание'); ?>
<?php echo $form->textArea($model2,'[$i]description',array('size'=>60,'maxlength'=>200)); ?>
<?php echo $form->error($model2,'description'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model2,'Язык'); ?>
<?php echo $form->dropDownList($model2,'[$i]lang',array('ru'=>'ru','en'=>'en','ua'=>'ua')); ?>
<?php echo $form->error($model2,'lang'); ?>
</div>
<?php ?>
<?php endforeach;?>
Help please
It would be something similar to this:
foreach ( $_POST[Model Name] as $i => $y ){
$var name[$i] = new Model Name;
$var name[$i]->title = $_POST[Model Name][$i][title]
...
}
var_dump the post ($_POST), object makes it easier to see.
I want two posts at each slide. but getting only one slide. I am new in programming, please help me.
$widget_id = $widget->id.'-'.uniqid();
$settings = $widget->settings;
$navigation = array();
$captions = array();
$i = 0;
?>
<div id="slideshow-<?php echo $widget_id; ?>" class="wk-slideshow wk-slideshow-revista-articles" data-widgetkit="slideshow" data-options='<?php echo json_encode($settings); ?>'>
<div>
<ul class="slides">
<?php foreach ($widget->items as $key => $item) : ?>
<?php
$navigation[] = '<li><span></span></li>';
$captions[] = '<li>'.(isset($item['caption']) ? $item['caption']:"").'</li>';
/* Lazy Loading */
$item["content"] = ($i==$settings['index']) ? $item["content"] : $this['image']->prepareLazyload($item["content"]);
?>
<li>
<article class="wk-content clearfix"><?php echo $item['content']; ?></article>
</li>
<?php $i=$i+1;?>
<?php endforeach; ?>
</ul>
<?php if ($settings['buttons']): ?><div class="next"></div><div class="prev"></div><?php endif; ?>
<?php echo ($settings['navigation'] && count($navigation)) ? '<ul class="nav">'.implode('', $navigation).'</ul>' : '';?>
<div class="caption"></div><ul class="captions"><?php echo implode('', $captions);?></ul>
</div>
</div>
http://i.stack.imgur.com/sy1ih.png
you're missing the { after the foreach and at the end of the loop.
<?php foreach ($widget->items as $key => $item) {
$navigation[] = '<li><span></span></li>';
$captions[] = '<li>'.(isset($item['caption']) ? $item['caption']:"").'</li>';
/* Lazy Loading */
$item["content"] = ($i==$settings['index']) ? $item["content"] : $this['image']->prepareLazyload($item["content"]);
?>
<li>
<article class="wk-content clearfix"><?php echo $item['content']; ?></article>
</li>
<?php
$i=$i+1;
}
?>
Your foreach syntax looks fine. That syntax is a lot easier for some people to read when embedded in HTML than the traditional braces.
Can I ask what the $this variable refers to? I don't see this instantiated anywhere in your code? Is it supposed to be $item instead?
$settings['index'] never changes within the loop, however $i does.
Change to: ($i<2)
Im looking to echo the value of my array key out into the view for this controller. I cant quite figure it out. So for the first feed I want to echo mmafighting into the of the view. Then it would loop through the rest.
Here is my controller code:
function index()
{
$this->load->library('simplepie');
$feeds = array('mmafighting' => 'http://www.mmafighting.com/rss/current',
'bbc' => 'http://feeds.bbci.co.uk/news/world/us_and_canada/rss.xml',
'bloodyelbow' => 'http://www.bloodyelbow.com/rss',
'ufc' => 'http://www.ufc.com/rss/news',
'hackernews' => 'http://news.ycombinator.com/rss',
'msnbc' => 'http://www.msn.com/rss/news.aspx',
'msnbc2' => 'http://www.msn.com/rss/msnmoney.aspx',
'msnbc3' => 'http://www.msn.com/rss/msnshopping_top.aspx'
);
foreach ($feeds as $site=>$url)
{
$data['feed'][$site] = new SimplePie();
$data['feed'][$site]->set_feed_url($url);
$data['feed'][$site]->set_cache_location(APPPATH.'cache');
$data['feed'][$site]->set_cache_duration(300);
$data['feed'][$site]->init();
$data['feed'][$site]->handle_content_type();
}
$this->load->view('feedsview', $data);
}
Here is my view code:
<?php
$feedCount = 0;
$rowCount = 0;
?>
<?php foreach ($feed as $site): ?>
<?php if ($site->data): ?>
<div class="feed">
<h2><?php // echo original array key here ?></h2>
<ul>
<?php $items = $site->get_items(0, 5); ?>
<?php foreach ($items as $item): ?>
<li><?php echo $item->get_title(); ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<?php $feedCount++; ?>
<?php if ($feedCount === 3) {
echo '<div style="clear:both;"> </div>';
$feedCount = 0;
$rowCount++;
if ($rowCount === 2) {
echo '<div style="width:1000px; margin-bottom:20px;height:100px; border:1px solid #252525; float:left;">images</div>';
}
} ?>
<?php endforeach; ?>
I'm not sure i understand but what about doing this :
<?php foreach ($feed as $key => $site): ?>
<?php if ($site->data): ?>
<div class="feed">
<h2><?php echo $key ?></h2>
<ul>