I have this piece of code in one single file
//declaring something
$array=array();
$arraylst=/*retrieve from database query and sure this contains the correct result*/
<?php
if(!empty($array)):
?>
<div id="something">
<?php
$n=0;
foreach($arraylst as $key=>$val):
$array="span".$n;
//create a span and print out $val's property1
$n++;
endforeach;
$n=0;
foreach($array as $key=>$val):
//create a span and print out $val's property2
$n++;
endforeach;
</div>
<?php
endif;
?>
<script language="javascript">
var arr=[<?php echo json_encode($array); ?>]
//do something else
</script>
The output to the screen I see is only one "span"; that is if my arraylst size is 3, I can only see the first span because my database query is sorted ascendingly. The rest is not seen at all.
$array="span".$n; overwrites the array with a string.
Use array_push( $array, "span$n" ); to add an item to the array.
(Then you'll want to remove the [ and ] from around the json_encode as you'll have an array in $array).
You always set the value "span" to $array.
$array="span".$n;
You do not add it to the array you set the array to that value.
Use:
$array[] ="span".$n;
Related
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.
I have the following piece of HTML in a PHP app with an array including Group and Items. First I want to sort them by Groups, then within Groups have Items separated by comma (Item1, Item2, Item3), without ending comma.
<dl>
<?php $groupname = '' ?>
<?php foreach ($product['product_filters'] as $product_filter) { ?>
<?php if ($groupname != $product_filter['group']) { ?>
<?php $groupname = $product_filter['group']; ?>
<?php echo '<dd>' . $product_filter['group'] . '</dd>'; ?>
<?php } ?>
<dt>
<?php echo $product_filter['name']; ?>
</dt>
<?php } ?>
</dl>
I want to have a the following result, but I don't know how to manage it and which loop should I use:
Group 1
G1_Item_1, G1_Item_2
Group 2
G2_Item_1, G2_Item_2, G2_Item_3
You could use two loops: one to restructure your data into groups, and one just for outputting it in the desired format. Note that you used <dt> and <dd> in the opposite sense: the groups are the titles, so use <dt> for them.
Also, your code becomes much more readable if you don't open and close the php tag on every line. Try to make code blocks that don't have such interruption: it will make it so more readable.
Here is the suggested code:
<?php
// Create a new structure ($groups): one entry per group, keyed by group name
// with as value the array of names:
foreach ($product['product_filters'] as $product_filter) {
$groups[$product_filter['group']][] = $product_filter['name'];
}
// Sort it by group name (the key)
ksort($groups);
// Print the new structure, using implode to comma-separate the names
foreach ($groups as $group => $names) {
echo "<dt>$group</dt><dd>" . implode(', ', $names) . "</dd>";
}
?>
See it run on eval.in.
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...
I store post IDs in an array. I would like to loop through the array and display the IDs within a <div> containing <p> and <ul> tags, but only when at least one ID is in the array. If the array is empty no html can be returned. This implies that I should use some kind of if statement before the loop. Needless to say, my php skills are pretty basic and after two days of trying hard I am getting nowhere. Grateful for help!
My code (using Wordpress)
$postids = array();
...
$postids [] = $post->ID; //stores the post IDs in the array
Here is an update. I apologize for posting all this code as its quite messy with many things going on. It's the second loop of three (or more). The IDs displayed in a near identical first loop have been passed on. Only those IDs which have not been retrieved by the previous loop are displayed in order not to show any duplicate posts.
I have tried to remove all HTML markup and query the $postids with a new WP_Query after but that retrieves all posts I have ever created. I am pretty sure that's the right way to continue although I am obviously doing something wrong.
<?php
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$first_tag = $tags[1]->term_id;
$args=array(
'tag__in' => array($first_tag),
'post__not_in' => array($post->ID),
'showposts'=>5, //Display this number of related posts
'ignore_sticky_posts'=>1
);
$postids = array();
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<ul id="relatedposts">';
while ($my_query->have_posts()) : $my_query->the_post(); if (!in_array($post->ID, $ids)) {; $postids [] = $post->ID; ?>
<li><?php the_title(); ?></li>
<?php }
$ids[]= $post->ID;
endwhile;
}
}
?>
</ul>
<?php if ($postids){ //$postids has at least one value set
echo '<div>Related posts</div>'; //Outputting the header text. This works! If there are no IDs in the array nothing is shown.
};
?>
This should work:
<?php
// assuming you have an array of ids called $postids
if(count($postids)){
echo "<div><ul>";
foreach($postids as $id){
echo "<li>$id</li>";
}
echo "</ul></div>";
}
?>
To break it down:
if(count($ids)){
count() returns the number of elements in the array $ids. Any number other than zero will evaluate to true and enter the if statement, zero will evaluate to false and the whole thing will be skipped.
foreach($ids as $id){
This loops through each element in the array $ids and assigns it to the variable $id. Hopefully the echo statements are self explanatory.
There are a couple of ways to do it.
if ($postids){ //$postids is TRUE (ie $postids is not an empty array)
//do your output
}
OR
if(count($postids) > 0){ //$postids has at least one value set
//do your output
}
Getting used to simple tests of true and !false is your friend
Mayhaps something like this? You should customize this code to retrieve the contents of the posts, or whatever you'd like to do.
<?php
$postIds = array(1, 2, 3, 4, 5);
?>
<html>
<head>
<title>Post IDs!</title>
</head>
<body>
<h1>Post IDs!</h1>
<?php if(empty($postIds)): ?>
<p>There are no post IDs :(</p>
<?php else: ?>
<ul>
<?php foreach($postIds as $postId): ?>
<li><?php echo $postId; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</body>
</html>
Thanks to the great help by Gordon, I now have a working solution. All html is removed from the messy original code above. The following if statement and foreach loop echoes out the html in a simple and convenient way. Styling the and tags is now very straightforward.
<?php
if(count($postids)){
echo "<div>Related posts<ul>";
foreach($postids as $id){
echo '<li>'.get_the_title( $id ).'</li>';
}
echo "</ul></div>";
}
?>
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;
}