How I can foreach array properly?
Code:
while ($row = mysqli_fetch_assoc($result))
{
if ($use_sef_links == true)
{
$sef_link = "{$row['title']} ({$row['home_team_name']} vs {$row['away_team_name']}) {$row['dt']}";
$sef_link = str_replace("-", " ", $sef_link);
$sef_link = preg_replace('#\s{1,}#', " ", $sef_link);
$sef_link = str_replace(" ", "-", $sef_link);
$sef_link = preg_replace('#[^a-zA-Z0-9-]#', "", $sef_link);
$sef_link .= '_m'. $row['id'] . '.html';
$row['link'] = $sef_link;
}
else
{
$row['link'] = 'match.php?id=' . $row['id'];
}
$matches[$row['season_name']][$row['game_day']][] = $row;
}
foreach ($matches as $match) { ?>
<section class="kode-pagesection margin-bottom-40" style="padding-top: 120px;">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="kode-section-title"> <h2>Coming <?php echo $match['season_name']; ?> season game - <?php echo $match['game_day']; ?> gameday</h2> </div>
<div class="kode-fixer-list">
<ul class="table-head thbg-color">
<li> <h5>Coming games</h5></li>
<li> <h5>Game starts</h5> </li>
<li> <h5>Stadium</h5> </li>
<li> </li>
</ul>
<ul class="table-body">
<li>
<img src="<?php echo $match['home_team_logo']; ?>" class="circle-icon" style="height:50px; width:50px;" alt="<?php echo $match['home_team_name']; ?>"> <?php echo $match['home_team_name']; ?>
<span>VS</span>
<img src="<?php echo $match['away_team_logo']; ?>" class="circle-icon" style="height:50px; width:50px;" alt="<?php echo $match['away_team_name']; ?>"> <?php echo $match['away_team_name']; ?>
</li>
<li><small><?php echo $match['dt']; ?></small></li>
<li><small><?php echo $match['stadium']; ?></small></li>
<li class="fixer-btn">
<?php echo $label_array[103]; ?>
</li>
</ul>
</div>
</div>
</div>
</div>
</section>
<?php } ?>
If I just print_r($matches); then I can see all seasons and games..
But I cant foreach matches as match..
I put image here to show what it shows if I print matches string.
Image:
https://gyazo.com/ad2ebed217e0507cf315103b52273225
I'd have written this as a comment, but there's not enough space....
Given the structure of your array $matches['season_name']['game_day'][]
I guess you want:
foreach($matches as $seasonName => $season) {
// print the season-header
echo $seasonName;
foreach($season as $gamedayID => $gameday) {
// print the gameday header
echo $gamedayID;
foreach($gameday as $match) {
// print the details from the match
echo $match['title'];
}
}
}
This is the version for grouping by season.
See my comments for explanations!
Too many unnecessary nesting though!
Btw you just need to use foreach (foreach array_expression as $key => $value) and array selector properly. For the inner arrays there'll be no advantage via using foreach, since you've got only one index array_expression as :
(foreach $matches as $matchIndex => $matchDetails){
$currentMatch = $matchDetails[0];
print_r($currentMatch);
// or whatever you want to do with that
}
Related
I have data collection and getting detail by foreach loop, which is working fine.
But I want 3 in a single inside foreach loop.
For example:
<ol>
<div>
<li></li>
<li></li>
<li></li>
</div>
<div>
<li></li>
<li></li>
<li></li>
</div>
<div>
<li></li>
<li></li>
<li></li>
</div>
</ol>
I am using below code for displaying the data:
<ol class="product-items widget-viewed-grid">
<?php $iterator = 1; ?>
<div id="mp-list-items-<?php echo $block->getSliderId(); ?>" class="owl-carousel owl-theme">
<?php foreach ($items as $_item): ?>
<?php echo ($iterator++ == 1) ? '<li class="product-item product-slider"">' : '</li><li class="product-item product-slider"">' ?>
<div class="slider-product-item-info">
<div class="product details slider-product-item-details">
<strong class="product name product-item-name">
<a title="<?php echo $block->escapeHtml($_item->getName()) ?>" href="<?php echo $block->getProductUrl($_item) ?>">
<?php echo $block->escapeHtml($_item->getName()) ?>
</a>
</strong>
</div>
</div>
<?php echo ($iterator == count($items) + 1) ? '</li>' : '' ?>
<?php endforeach ?>
</div>
</ol>
echo "<ol>";
for( $i=0; $i<3; $i++ ) {
echo "<div>";
for($j=0; $j<3; $j++) {
echo "<li>";
echo "</li>";
}
echo "</div>";
}
echo "</ol>";
You have to use nested loops. Outer loop for product <div> and inner loop for product items <li>.
For Example
foreach($products as $product){
echo "<div class='product'>";
//Now you can call sql query to get items by product id
foreach($items as $item){
echo "<li class='list-item'>" . $item->name . "</li>"; //assuming $item has name property
} //end of inner loop
echo "<div class='product'>";
} //end of outer loop
I am running a while loop to return all the results of a mysqli query but I want to use php to group the results.
My code is
while($row = mysqli_fetch_array($result))
{
if($row['total'] >0)//row['total'] is found out within the query itself
{
$recipeWords = str_word_count(preg_replace('/\s{1,}(and\s*)*/', ' ', $row['title']));
if($countTerms == $recipeWords)
{
echo "<h2>Exact Match</h2>";?>
<div class="fluid recipeContainerSmall">
<a href="recipe_details.php?id=<?php echo $row['recipeID']?>">
<img src="images/recipes/<?php echo $row['image']?>" alt="<?php echo $row['title']?>" title="<?php echo $row['title']?>" />
<h4><?php echo $row['title']?></h4></a>
</div><?php
}
elseif($countTerms == ($recipeWords-1))
{
echo "<h2>Closest Matches</h2>";?>
<div class="fluid recipeContainerSmall">
<a href="recipe_details.php?id=<?php echo $row['recipeID']?>">
<img src="images/recipes/<?php echo $row['image']?>" alt="<?php echo $row['title']?>" title="<?php echo $row['title']?>" />
<h4><?php echo $row['title']?></h4></a>
</div><?php
}
else
{
echo "<h2>Other Suggestions</h2>";?>
<div class="fluid recipeContainerSmall">
<a href="recipe_details.php?id=<?php echo $row['recipeID']?>">
<img src="images/recipes/<?php echo $row['image']?>" alt="<?php echo $row['title']?>" title="<?php echo $row['title']?>" />
<h4><?php echo $row['title']?></h4></a>
</div><?php
}
}
}?>
What I am trying to do is group the results so that:
all the exact matches are displayed first
then I want all the records where all but one of the keywords are found
then the rest
at the moment they are being displayed on what seems a random order.
<?php
while($row = mysqli_fetch_array($result))
{
if($row['total'] >0)//row['total'] is found out within the query itself
{
$recipeWords = str_word_count(preg_replace('/\s{1,}(and\s*)*/', ' ', $row['title']));
$exactMatches = "";
$closestMatches = "";
$otherSuggestions = "";
if($countTerms == $recipeWords)
{
$exactMatches .= <<<EXACT_MATCH
<h2>Exact Match</h2>
<div class="fluid recipeContainerSmall">
<a href="recipe_details.php?id={$row['recipeID']}">
<img src="images/recipes/{$row['image']}" alt="{$row['title']}" title="{$row['title']}" />
<h4>{$row['title']}</h4></a>
</div>
EXACT_MATCH;
}
elseif($countTerms == ($recipeWords-1))
{
$closestMatches .= <<<CLOSEST_MATCH
<h2>Closest Match</h2>
<div class="fluid recipeContainerSmall">
<a href="recipe_details.php?id={$row['recipeID']}">
<img src="images/recipes/{$row['image']}" alt="{$row['title']}" title="{$row['title']}" />
<h4>{$row['title']}</h4></a>
</div>
CLOSEST_MATCH;
}
else
{
$otherSuggestions .= <<<OTHER_SUGGESTIONS
<h2>Other Suggestions</h2>
<div class="fluid recipeContainerSmall">
<a href="recipe_details.php?id={$row['recipeID']}">
<img src="images/recipes/{$row['image']}" alt="{$row['title']}" title="{$row['title']}" />
<h4>{$row['title']}</h4></a>
</div>
OTHER_SUGGESTIONS;
}
// ECHO in the order you want to...
echo $exactMatches . $closestMatches . $otherSuggestions;
}
}?>
As asked by you above, please try this code.
Please note that I've used HEREDOCS to simplify the parsing of the data.
so i guess this is pretty easy for most of you, but i can't figure this out.
im trying to make the links dynamic eg: href="linkname(#1 or #2 etc)"
any ideas?
<?php if ($top_fundraisers && is_array($top_fundraisers)): ?>
<?php foreach ($top_fundraisers as $index => $fundraiser): ?>
<a title="" class="fancybox" href="linkname(GENERATE CODE HERE)">
<div class="top-fundraiser">
<div id="newo<?php print htmlentities($index + 1); ?>" class="top-fundraiser-image">
<img src="<?php
if($fundraiser['member_pic_medium']) {
print htmlentities($fundraiser['member_pic_medium']);
} else {
print $template_dir . '/images/portrait_placeholder.png';
}
?>"/>
</div>
</div>
</a>
<?php endforeach;?>
<?php endif; ?>
Suppose below is what you need.
<?php if ($top_fundraisers && is_array($top_fundraisers)): ?>
<?php foreach ($top_fundraisers as $index => $fundraiser): ?>
<a title="" class="fancybox" href="linkname(#<?php echo $index + 1; ?>)">
<div class="top-fundraiser">
<div id="newo<?php print htmlentities($index + 1); ?>" class="top-fundraiser-image">
<img src="<?php
if($fundraiser['member_pic_medium']) {
print htmlentities($fundraiser['member_pic_medium']);
} else {
print $template_dir . '/images/portrait_placeholder.png';
}
?>"/>
</div>
</div>
</a>
<?php endforeach;?>
<?php endif; ?>
I have this
<?php
foreach ($results as $row):
if ($row['title'] == "") $row['title'] = date('d-m-Y', strtotime($row['date']));
if (strlen($row['text']) > 100) $row['text'] = substr($row['text'], 0, 100) . "...";
?>
<div>
<a href="<?php echo $row['url'] ?>">
<img src="<?php echo $row['image'] ?>" alt="<?php echo $row['title'] ?>" />
<h1><?php echo $row['title'] ?></h1>
<p><?php echo $row['text']; ?></p>
</a>
</div>
<?php endforeach ?>
Right after the foreach starts I do some "house cleaning" where I substitute the date if there is no title and reduce the text to 100 characters etc.
Repeating this over and over is not very efficient, so it would be better to create a function right?
My question is how do I do this?
Thanks for your help
Try rewriting your code like this. Just add more of your required functionality to the processRowData() function.
<?php
function processRowData($row) {
if ($row['title'] == "") {
$row['title'] = date('d-m-Y', strtotime($row['date']));
}
// Do more with other elements from $row ...
// when done, return the modified $row array
return $row;
}
?>
<?php
foreach ($results as $row) {
// Alter the row data with your function
$row = processRowData($row);
?>
<div>
<a href="<?php echo $row['url'] ?>">
<img src="<?php echo $row['image'] ?>" alt="<?php echo $row['title'] ?>" />
<h1><?php echo $row['title'] ?></h1>
<p><?php echo $row['text']; ?></p>
</a>
</div>
<?php } ?>
I'm trying to create a link based on a URL variable using only the last five digits of its respective line of XML data.
For example, if the XML link is http://events.stanford.edu/events/213/21389 how can I create this link a href="e/?i=21389?
Here's my page, XML and code:
<?php
// Build the XML file path, using URL variable $c (above)
$c = $_GET['c'];
$p ="http://events-prod.stanford.edu/xml/byCategory/";
$e = "/mobile.xml";
$file = "$p$c$e";
$xml = simplexml_load_file($file);
?>
<h1><?php echo $xml->title; ?></h1>
Home
</div><!-- /header -->
<div data-role="content">
<?php // Only display if there are events ?>
<?php if (isset($xml->Event->title)) { ?>
<ul data-role="listview">
<?php foreach($xml->Event as $event) { ?>
<li>
<a href="<?php echo $event->link; ?>">
<?php if ($event->Media->url != null) { ?>
<img src="<?php echo $event->Media->url;?>" alt="<?php echo $event->title;?> thumbnail" />
<?php } ?>
<h3><?php echo $event->title; ?></h3>
<p><strong><?php echo $event->beginDate; ?> at <?php echo $event->beginTime; ?></strong></p>
<p><?php echo $event->locationText; ?></p>
</a>
</li>
<?php } ?>
</ul>
<?php } else { ?>
<?php echo '<p>There is currently nothing scheduled for ', $xml->title, '.</p>';?>
<?php } ?>
I'm using short tags, because I think you'll agree it's easier now to read the code as oppose to before.
<?
$controller ="http://events-prod.stanford.edu/xml/byCategory/";
$category_id = $_GET['c'];
$category_id = 0;
$xml = "/mobile.xml";
$url = $controller . $category_id . $xml;
$xml_object = simplexml_load_file($url);
?>
<div>
<h1><?= $xml_object->title ?></h1>
Home
</div>
<div data-role="content">
<? if (!empty($xml_object->Event->title)): ?>
<ul data-role="listview">
<? foreach($xml_object->Event as $event): ?>
<li>
<?
$pattern = '/[0-9]+$/';
$matches = array();
preg_match($pattern, $event->link, $matches);
$my_link = 'e/?i=' . $matches[0];
?>
<a href="<?= $my_link ?>">
<? if (!empty($event->Media->url)): ?>
<img src="<?= $event->Media->url ?>" alt="<?= $event->title ?> thumbnail" />
<? endif; ?>
<h3><?= $event->title ?></h3>
<p><strong><?= $event->beginDate ?> at <?= $event->beginTime ?></strong></p>
<p><?= $event->locationText ?></p>
</a>
</li>
<? endforeach; ?>
</ul>
<? else: ?>
<? echo '<p>There is currently nothing scheduled for ', $xml_object->title, '.</p>'; ?>
<? endif; ?>
</div>