Multiple foreach loops - php

I'd like to have 2 foreach loops for 2 arrays like that, I know it's wrong:
$properties has 6 items and $set_properties has 11 items
<?php if(!empty($properties)) : foreach ($properties as $prop) : ?>
<?php if(!empty($set_properties)) : foreach ($set_properties as $set_prop) : ?>
<?php endforeach; endif; ?>
<?php endforeach; endif; ?>
What would be the right way, because right now I'm getting too many loops if I want to echo something out ($prop->ID).
My goal is to make dropdown selectors($properties) and have $set_properties as options.

Try the following snippet, which I commented to hopefully help you understand.
//check if properties is empty, if not, loop through them.
if(!empty($properties)):
foreach ($properties as $prop):
//check if $set_properties is empty, if not create select element
if(!empty($set_properties)):
//loop through properties, generate select element for current index
//obviously you can do proper select element naming and everything I just don't know your markup
//notice I do this after checking if the options fields are empty, so that way it only appears if there are options associated with it.
echo $prop->ID.": <select>";
//loop through set_properties, generate options
foreach ($set_properties as $set_prop):
echo "<option value='{$set_prop->ID}'>{$set_prop->Name}</option>";
endforeach;
//end select element, so next iteration will make a new one.
//again, inside the check for $set_properties because the select element will only exist if options exist
echo "</select>";
endif;
endforeach;
endif;
In your original code you switch in and out of PHP very often, and that is really not necessary, it makes the code look messy and it's harder to format. Just write it all in PHP as there isn't much HTML that goes into it. You should only switch in/out of PHP if you are only trying to insert a variable into an element, or if there is a lot of HTML.

Related

Dynamically populating wordrpess shortcode from an array

I am trying to customize output of wordpress smart grid plugin. My aim is to add list of images into a section and output them through the plugin. The image list has to be wrapped by the plugin shortcode. Which I have done, only problem is looping. Here is my code
<div class="p_details_right">
<?php
//print_r($partner_pictures);
$pic_bucket = []; //empty array to hold list of image id to be used within the wordpress default gallery shortcode
?>
<?php
foreach ($partner_pictures as $key => $item) {
array_push($pic_bucket, $key); // populating the array which holds image id
?>
<?php
}
//print_r($pic_bucket);
?>
<?php echo do_shortcode("
[smart-grid]
[gallery ids='$pic_bucket[0],$pic_bucket[1],$pic_bucket[2]'] // <----- PROBLEM . Currently doing it statically but I need to be able to add populate the id element of the shortcode dynamically based on the $pic_bucket array.
[/smart-grid]
"); ?>
</div>
Currently outputting the gallery by statically adding array element but I need to be able to add populate the id element of the shortcode dynamically based on the $pic_bucket array. Tried to do looping but does not work. I am missing something very basic.
Sollution
convert Array to string and assign ids variable with that.
<div class="p_details_right">
<?php
//print_r($partner_pictures);
$pic_bucket = [];
?>
<?php
foreach ($partner_pictures as $key => $item) {
array_push($pic_bucket, $key);
?>
<?php
}
//print_r($pic_bucket);
$str = implode(',',$pic_bucket);
?>
<?php echo do_shortcode("
[smart-grid]
[gallery ids='$str']
[/smart-grid]
"); ?>
</div>
You can join an array of ID's together with implode(',',$array)

Multiple select values to render static Block Content

I've managed to render static blocks through a custom attribute on a per product basis, which is great, however it only seems to work with drop downs, I would like to use a multi select so i could allow the administrator to select multiple static blocks in one are, rather than have multiple drop down menus.
here's the code for the drop down
<?php
$cmsstatic=$_product->getResource()->getAttribute('attributename')->getFrontend()->getValue ($_product);
echo $this->getLayout()->createBlock('cms/block')->setBlockID($cmsstatic)->tohtml();
?>
I managed to get the value of the attribute options out for a multi select:
<?php if($_product->getResource()->getAttribute('product_featured_attribute_3')->getFrontend()->getValue($_product)): ?>
<ul><li><?php
$_comma = ",";
$_list = "</li><li>";
echo str_replace($_comma,$_list,$_product->getResource()->getAttribute('attributename')->getFrontend()->getValue($_product)) ?>
</li></ul>
<?php endif; ?>
but i'm having problems getting it to output the value as a static block. Any ideas?
as i understood you want to echo all the block content which id's are defined in product attribute.
For that you can try this:
<?php
$cmsstatic=$_product->getResource()->getAttribute('attributename')->getFrontend()->getValue($_product);
$blockids = explode(",", $cmsstatic);
foreach($blockids as $kry=>$value)
{
echo $this->getLayout()->createBlock('cms/block')->setBlockID($value)->tohtml();
}
?>

Showing the first element in an foreach array in HTML

I have an array $category['transactions']. It stores data as follow:
ID Name Phone
1 Test Test2
2 Test3 Test4
It's because I use the same array for different purpose, at one of the scenario is to show only the first record in this array. I don't what to change the coding in php nor creating a different parameter. What can I improve based on the following coding in html to get the first record only in this array?
<?php foreach($category['transactions'] as $transaction) { ?>
<div><?php echo $transaction['id']; ?></div>
<div><?php echo $transaction['name']; ?></div>
<?php } ?>
replace your code with.
<?php $firstRow=reset($category['transactions']);
echo '<div>',$firstRow['id'],'</div>';
echo '<div>',$firstRow['name'],'</div>';
?>
You don't need to iterate through the array to get the first element.
You don't even need the foreach to get the first element. Just use array_values():
$first = array_values($category['transactions')[0]
try this..
<?php
foreach($category['transactions'] as $transaction)
{
echo $transaction['id'];
break;
}
?>
and no need to use multiple php tags...

How to get only one result from foreach(PHP)

The code loop an array and display all views for a user. Now things changed and I just need to display one result from a foreach loop. How do I do that?
<table class="report_edits_table">
<thead>
<tr class="dates_row">
<?php foreach($report['edits'] as $report_edit) : ?>
<td colspan="2" report_edit_id="<?php echo $report_edit['id'] ?>"><div class="date_container">
<?php if($sf_user->hasCredential(Attribute::COACHING_EDIT_ACCESS)) : ?>
<span class="ui-icon ui-icon-trash">Remove</span>
<?php endif?>
<?php echo "View " . link_to($report_edit['created'], sprintf('coaching/viewReportEdit?reportedit=%s', $report_edit['id']), array('title' => 'View This Contact')) ?> </div></td>
<?php endforeach ?>
</tr>
</thead>
<tbody>
<?php foreach($report['edits_titles'] as $index => $title) : ?>
<tr class="coach_row">
<?php for ($i=max(0, count($report['edits'])-2); $i<count($report['edits']); $i++) : $report_edit = $report['edits'][$i] ?>
<td class="name_column"><?php echo $title ?></td>
<td class="value_column"><?php echo $report_edit[$index] ?></td>
<?php endfor ?>
</tr>
<?php endforeach ?>
</tbody>
Use the break command for simple conversion:
<?php for ... ?>
... stuff here ...
<?php break; ?>
<?php endfor ... ?>
A better solution would be to remove the foreach completely.
It sounds like you want to grab the first element from an array without having to loop through the rest of them.
PHP provides a set of functions for situations like this.
To get the first element in an array, start off using the reset() function to position the array pointer to the start of the array, then use the current() function to read the element that the pointer is looking at.
So your code would look like this:
<?php
reset($report['edits']);
$report_edit = current($report['edits']);
?>
Now you can work with $report_edits without having to use a foreach() loop.
(note that the array pointer does actually start by default at the first record, so you could skip the reset() call, but it's best practice not to do that because it might have been changed elsewhere in your code without you realising it)
If you want to move on to the next record after that, you can use the next() function. As you can see, if you wanted to, it would theoretically be possible to use these functions to write an alternative type of foreach() loop. There wouldn't be any point in using them them that way, but it's possible. But they do allow more fine-grained control over the array, which is handy for situations like yours.
Hope that helps.
Plenty of ways
Access the index of the array element in question directly
Update whatever logic fetches/generates the array to only return the element of interest
Use a for loop that terminates after a single loop
array_filter your array to get the element of interest
Break at the end of your foreach loop so it terminates after the first iteration
Conditionally check your index in the foreach loop and only output markup if the index matches the element of interest
And so on
I'd recommend just getting the array element of interest (number 2 on the list) as it means less data bouncing around your code (and probably between your PHP box and the database if you're populating the array from an SQL server)
Simplest method?
Place a break as the last line of your foreach. It'll execute once, then quit. (As long as which element you stop on is of no importance).
Secondary method: use array_pop or array_shift on your $report['edits'] or $report['edits_titles'] to get on element, lose the for loop, and reference the element you just retrieved.
For example:
//
// current
//
foreach ($report['edits'] as $report_edit) :
/* markup */
endforeach;
//
// modified version
//
$report_edit = array_shift($report['edits']);
/* markup */
Use <?php break ?> before <?php endforeach ?>
example ::
<?php
foreach ($this->oFuelData AS $aFuelData ) {
echo $aFuelData['vehicle'];
break;
}
?>
You can also use it for reference
foreach($array as $element) {
if ($element === reset($array))
echo $element;
if ($element === end($array))
echo $element;
}

Iterating through a foreach loop - only show 1 item rather than all

I've setup a Google map that has several plotted markers, each one when clicked on has a little popup with info within.
I'm using the following code to show the company name per plotted marker, but it's going through the foreach loop and showing ALL the company names within one popup.
How can loop through and show one company name per plotted marker? I need it to show the first company in the list on the first marker, the second company in the list on the second marker and so on.
// Setting the content of the InfoWindow
infowindow.setContent('
<?php $pages = get_pages(array('child_of' => $post->ID, 'sort_column' => 'menu_order')); foreach($pages as $post) {
setup_postdata($post);
$fields = get_fields(); ?>
<p><?php echo $fields->company_name; ?></p>
<?php } wp_reset_query(); ?>
');
Look at your code. what a mess! You would never have missed these obvious mistakes, if you would care to structure your code well! Don't write all your code on one line! Use best practice for code style!
Don't put all that PHP code inside the javascript function.
Instead, use a variable $contentMarkup, store everything in there and in the end echo this variable into the javascript code.
<?php
$contentMarkup = '';
//do all your stuff like
$contentMarkup .= '<p>';
$contentMarkup .= $fields->companyName;
$contentMarkup .= '</p>';
?>
infowindow.setContent('<?php echo $contentMarkup; ?>');
Regarding your actual question: If you want to generate more than one tooltip/window/younameit, they have to have unique identifiers so you can create one for each company. But to say more I'd need to know a bit more about what exactly you're trying to do. What information is available and from what source.
show what you want based on if statement inside foreach loop

Categories