I need some help with solving duplicating problem. To deal:
I have 2 filed custom meta
It displays this way :
Only 2 image placed, but it duplicate <li>.
First and third <li> is only video, second and fourth works fine, looks like this :
foreach($slider_xml->childNodes as $slider){
$test_test = get_post_meta(9,'test_1', false);
foreach($test_test as $test_test){
echo '<li class="img-vid-slide">';
echo '<iframe src="https://www.youtube.com/embed/'. $test_test . '" frameborder="0" allowfullscreen></iframe>';
}
echo '<div class="img-slide" >';
if($link_type == 'Lightbox'){
$image_full_url = wp_get_attachment_image_src(find_xml_value($slider, 'image'), 'full');
echo '<a href="' . $image_full_url[0] . '" data-rel="prettyPhoto[flexgal]" title="" >';
}else if($link_type != 'No Link'){
echo '<a href="' . $link . '" >';
}
echo '<img class="'. $i .'" src="' . $image_url[0] . '" alt="' . $alt_text . '" />';
echo '</div>';
if( !empty($title) ){
echo '<div class="flex-caption gdl-slider-caption">';
echo '<div class="gdl-slider-title">' . $title . '</div>';
echo '<div class="slider-title-bar"></div>';
echo $caption;
echo '</div>'; // flex-caption
}
if($link_type != 'No Link'){
echo '</a>';
}
echo '</li>';
}
I find solution.
Filed custom fields: prntscr.com/7oqqvt
I named them like "name_1","name_2"..."name_4".
$i is equal of last nubmer in custom field.
Result on screen: prntscr.com/7oqsaw
$i = 1;
while ($i <= 3):
foreach( $slider_xml->childNodes as $slider ){
// ======= SAME AS FIRST ====== //
$test_test = get_post_meta(9,'test_'. $i .'', true);
echo '<iframe src="https://www.youtube.com/embed/'. $test_test . '" frameborder="0" allowfullscreen></iframe>';
echo '<div class="img-slide" >';
if($link_type == 'Lightbox'){
// ======= SAME AS FIRST ====== //
}
echo '</li>';
$i++;
}
endwhile;
Works fine for me, do what i searching for!
Thanks, Greg, for a little hint, but i go for "while" instead of "for"! Good luck
Don't use the a foreach inside a foreach loop. It a function problem.
Use the alternative "for" loop instead of the double foreach.
Related
Forgive me if this is simple but I have a for each loop that searches JSON data for results from a search. I then have some preg_match statements that will look at some of the tags within the JSON and if their is a match display the thumbnail in a div. and currently this all works. But it currently displays every result in its own Div and i want just five divs with multiple images within if there is a match.
foreach ($hits as $hit)
{
$target = $hit->metadata->baseName;
$target1 = $hit->metadata->cf_imageType;
if(preg_match("/_cm/i",$target)) {
echo '<div id="div5">';
echo '<h2>Creative</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/_SS/i",$target)) {
echo '<div id="div6">';
echo '<h2>Styled</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/_SH/i",$target)) {
echo '<div id="div7">';
echo '<h2>Group</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/still life/i",$target1) && preg_match("/_sm_00|_sd_00/i",$target)) {
echo '<div id="div8">';
echo '<h2>Cutout</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/worn/i",$target1)) {
echo '<div id="div9">';
echo '<h2>Worn</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
}
I cant quite figure out how to accomplish this, would it be the case of putting the results into an array and then displaying the results within the div?
Any help would be greatly appreciated.
You are right and answered the question yourself :)
Collect the results in a first step and create the markup in a second step. Something like this will do it:
$creative = [];
$styled = [];
/* ... */
function getHitInfos($theHit)
{
return [
"url" => $theHit->thumbnailUrl,
"name" => $theHit->metadata->baseName
];
}
function printResults($results, $title) {
echo '<div>';
echo '<h2>'.$title.'</h2>';
foreach ($results as $key => $val) {
echo "<img src='" . $val["url"] . "' alt='error'>";
echo $val["name"];
}
echo '</div>';
}
foreach ($hits as $hit)
{
$target = $hit->metadata->baseName;
$target1 = $hit->metadata->cf_imageType;
echo '<div>';
if(preg_match("/_cm/i",$target)) {
$creative[] = getHitInfos($hit)
}
if(preg_match("/_SS/i",$target)) {
$styled[] = getHitInfos($hit)
}
/* ... */
}
printResults($creative, "Creative");
printResults($styled, "Styled");
/* ... */
Disclaimer: My last contact with php is some years ago, but I hope you will see the point here.
(I also created some helping functions to DRY the code)
I am currently trying to create a class schedule which I pull from my Sql Server database with PHP and I am trying to get the layout output as well as the data as I am grouping the resources.
These groupings are nested such as:
-DAY
--TIME
---CLASS
----STUDENTS
And should output like this:
However, I am getting this:
My current output is working, however, it is only on the first loop, then everything goes haywire. I am assuming there is an erroneous </div> tag somewhere in my code yet I cannot for the life of me find it.
My php code is a function that is delcare as such:
<div class="mainScheduleWrapper">
<?php daySchedule(); ?>
</div>
My php code is as such:
function daySchedule() {
global $conn;
$dayScheduleQuery = 'SET DATEFIRST 1
SELECT [DAY].[DAY] AS [DAY], CLASS.CLASSTIME AS CLASSTIME, CLASSLEVEL.CLASSLEVEL AS CLASSLEVEL, CLASS.MAXSTUDENT AS MAXSTUDENT, INSTRUCTOR.FIRSTNAME AS INSTRUCTOR, STUDENT.FIRSTNAME AS STUDENTFIRST, STUDENT.SURNAME AS STUDENTLAST, STUDENT.DOB AS STUDENTDOB
FROM STUDENT JOIN BOOKING ON STUDENT.ID = BOOKING.STUDENTID JOIN CLASS ON CLASS.ID = BOOKING.CLASSID JOIN CLASSLEVEL ON CLASS.CLASSLEVELID = CLASSLEVEL.ID JOIN [DAY] ON CLASS.CLASSDAY = [DAY].ID JOIN INSTRUCTOR ON CLASS.INSTRUCTORID = INSTRUCTOR.ID
WHERE [DAY].ID = (DATEPART(dw, GETUTCDATE() AT TIME ZONE \'AUS Eastern Standard Time\'))
ORDER BY CLASS.CLASSTIME ASC, INSTRUCTOR.FIRSTNAME ASC, CLASSLEVEL.CLASSLEVEL ASC';
// COUNTERS
$t = 0;
$i = 0;
//VARIABLES FOR DAY SCHEDULE
$classDay = NULL;
$classTime = NULL;
$classInstructor = NULL;
$closeClass = false;
$closeAll = false;
$queryConnector = $conn->query($dayScheduleQuery);
foreach ($queryConnector as $schedule) {
// CLASS DAY HEADER
if ($classDay != $schedule['DAY']) {
echo '<div class="grid-1">';
echo '<h1>' . $schedule['DAY'] . '</h1>';
echo '</div><!-- Day closed! -->';
$classDay = $schedule['DAY'];
}
// CLASS TIME HEADER
if ($classTime != $schedule['CLASSTIME']) {
if($classTime != $schedule['CLASSTIME'] && $t > 0) {
$closeAll = true;
goto closeAll;
}
echo '<div class="grid-12-noGutter scheduleContainer">'; //NON-CLOSED
echo '<h1>' . 'T = ' . $t . '</h1>';
echo '<div class="grid-middle-center col scheduleTimeTab">';
// FIX 3 DIGIT MILITARY TIME
if (strlen($schedule['CLASSTIME']) < 4) {
$classScheduleTime = '0' . $schedule['CLASSTIME'];
} else {
$classScheduleTime = $schedule['CLASSTIME'];
}
echo '<p>' . date('g:i A', strtotime($classScheduleTime)) . '</p>';
echo '</div>'; //CLOSE TIME TAB
echo '<div class="innerSchedule">'; // NON-CLOSED
$classTime = $schedule['CLASSTIME'];
$t += 100;
}
// INSTRUCTOR HEADER
if ($classInstructor != $schedule['INSTRUCTOR']) {
if ($classInstructor != $schedule['INSTRUCTOR'] && $i > 0) {
$closeClass = true;
goto closeClassWrapper;
}
echo '<div class="classWrapper">';
echo '<h1>' . 'I =' . $i . 'T = ' . $t . '</h1>';
echo '<div class="grid-3-middle classHeader">';
echo '<div class="col classHeaderCell' . classLevelColour($schedule['CLASSLEVEL']) . '">' . $schedule['CLASSLEVEL'] . '</div>';
echo '<div class="col classHeaderCell">' . $schedule['INSTRUCTOR'] . '</div>';
echo '<div class="col classHeaderCell">Max' . ' ' . $schedule['MAXSTUDENT'] . '</div>';
echo '</div>';
echo '<div class="grid-4-middle" id="studentHeaders">';
echo '<div class="col"><h6>Student Name</h6></div>';
echo '<div class="col"><h6>Student Birthday</h6></div>';
echo '<div class="col"><h6>Class Level</h6></div>';
echo '<div class="col"><h6>Attendance</h6></div>';
echo '</div>';
$classInstructor = $schedule['INSTRUCTOR'];
$i += 100;
}
echo '<div class="grid-4 studentRow">';
echo '<div class="col">';
echo '<span class="studentCell">' . $schedule['STUDENTFIRST'] . ' ' . $schedule['STUDENTLAST'] . '</span>';
echo '</div>';
echo '<div class="col">';
echo '<span class="studentCell">' . $schedule['STUDENTDOB'] . '</span>';
echo '</div>';
echo '<div class="col">';
echo '<span class="studentCell">' . $schedule['CLASSLEVEL'] . '</span>';
echo '</div>';
echo '<div class="col">';
echo '<span class="studentCell">--</span>';
echo '</div>';
echo '</div>';
// GOTO TAGS
closeClassWrapper: {
if ($closeClass === true) {
echo '</div>';
$closeClass = false;
$i = 0;
}
}
closeAll: {
if ($closeAll === true) {
echo '</div>';
echo '</div>';
echo '</div>';
$closeAll = false;
$t = 0;
$i = 0;
}
}
}
}
Any help would be greatly appreciated - even if it's to tell me I'm going about it the completely wrong way.
Kindest Regards
Michael Z
I wouldn't say you're going about it the completely wrong way, but a few red flags jumped out at me in your code.
The use of goto jumping is bad practice. It butchers your program flow and forces you to segregate tasks that shouldn't be kept apart. You marked the sections of code "// NON CLOSED" when there was a </div> missing, is there any purpose for that? How do you know the goto sections are reliable?
When you echo something like <div class="col">, without escaping the double-quotes (as in \" for every " character), it can be problematic. Your code can get mangled or misinterpreted, both on the PHP end or on the HTML end.
Like others have said, the use of PHP may be overkill here. Besides just sending the JSON, the rest could be handled with JavaScript.
This question already has answers here:
What is the difference between single-quoted and double-quoted strings in PHP?
(7 answers)
Closed 5 years ago.
i have the following code:
<?php
$events = Event::with('skoler')->get();
$skoleIsSet = $_GET['skoleId'];
$eventIsSet = $_GET['event'];
if($skoleIsSet && !$eventIsSet) {
foreach($events as $event) {
if($event['skole_id'] == $skoleIsSet) {
***$img = $event['img_url'];***
echo '<div id="events">';
***echo '<img src="$img" height="100" width="100"/>';***
echo '<h1>' . $event['title'] . '</h1>';
echo '<p>Beskrivelse: ' . $event['description'] . '</p>';
echo '<p>Pris: ' . $event['pris'] . '</p>';
echo '<p>Dato: ' . $event['date'] . '</p></div>';
}
}
}
else {
foreach ($events as $event) {
if ($event['skole_id'] == $skoleIsSet) {
$bg = $event['img_url'];
'<div id="events">';
echo '<h1>' . $event['title'] . '</h1>';
echo '<p>Beskrivelse: ' . $event['description'] . '</p>';
echo '<p>Pris: ' . $event['pris'] . '</p>';
echo '<p>Dato: ' . $event['date'] . '</p></div>';
}
}
?>
I am supposed to show all events, with a picture. The url for the pictures is in the img_url column in my db. What is wrong with line number 8 and 10? The strong font option is not working, but the lines im referring to is marked with 6x *'s.
Thanks!
echo '<img src="$img" height="100" width="100"/>';
You cannot include a variable directly into a string, if you're using single quotes. Either use double quotes (and escape the double quotes inside the string), or interrupt your string:
echo '<img src="' . $img . '" height="100" width="100"/>';
echo "<img src=\"$img\" height=\"100\" width=\"100\"/>";
I have a WordPress site and currently the code it set to create titles based on the page title. The titles are: Interior House Painting, Exterior House Painting and Commercial Painting. I would like to override the titles to remove the word "house". This is the code currently:
<?php
// interior_painting: 18
// exterior_painting: 25
// other services: 36
$page_ids = array(18, 25, 36);
$images = array('servicesInterior.jpg', 'servicesExterior.jpg', 'servicesOther.jpg');
foreach ($page_ids as $key => $page_id) {
$page_post = get_post($page_id);
$page_custom_key = 'home_page_info';
$page_link = $page_post->post_name;
$li_class = $page_id == 36 ? 'noMargin' : '';
$title = $page_id == 18 ? 'Interior Painting' : $page_post->post_title . " ";
$title = $page_id == 36 ? 'Commercial Projects' : $page_post->post_title . " ";
$title = $page_id == 25 ? 'Exterior Painting' : $page_post->post_title . " ";
echo '<li class="' . $li_class . '"> <a href="' . $page_link . '">';
echo '<img class="alignright size-full wp-image-349" title="servicesInterior" src="/wp-content/uploads/2011/04/' . $images[$key] . '" alt="" width="200" height="95" /></a>';
echo '<h2>' . $title . '</h2>';
echo get_post_meta($page_id, $page_custom_key, true);
echo '<a class="btn-find-more" href="' . $page_post->post_name . '">FIND OUT MORE</a></li>';
}
?>
The output is this: Interior House Painting, Exterior Painting, Commercial Painting. How do I get "house" removed from "Interior House Painting"?
$title = ucwords(trim(strtolower(str_replace('house', '', $page_post->post_title))));
Though, I am a little curious as to why you would not prefer to just remove the word from the title altogether.
ADDITIONALLY: Somebody else mentioned using preg_replace. That's also entirely possible, but it would be best to do a case-insensitive search:
$title = trim(preg_replace('/house/i', '', $page_post->post_title));
Just use preg_replace('House'|| 'house','',/*Variable Page title is in*/);
You could try replacing the line:
echo '<h2>' . $title . '</h2>';
With something like this:
if (is_page('Interior House Painting')) { echo '<h2>Interior Painting</h2>'; }
if (is_page('Exterior House Painting')) { echo '<h2>Exterior Painting</h2>'; }
else { echo '<h2>' . $title. '</h2>'; }
I'm trying to display the first row in one color and the second row in another color but my code displays the result twice in both colors for example lets say I have 5 results my code will double the results by displaying 10 results. How can I fix this problem?
Here is the php code.
while ($row = mysqli_fetch_assoc($dbc)) {
//first row
echo '<h3 class="title">' . $row['title'] .'</h3>';
echo '<div class="summary">' . substr($row['content'],0,255) . '</div>';
//second row
echo '<h3 class="title-2">' . $row['title'] .'</h3>';
echo '<div class="summary-2">' . substr($row['content'],0,255) . '</div>';
}
You need to change the class on each row:
$count = 0;
while ($row = mysqli_fetch_assoc($dbc)) {
if( $count % 2 == 0 ) {
$classMod = '';
} else {
$classMod = '-2';
}
//first row
echo '<h3 class="title' . $classMod . '">' . $row['title'] .'</h3>';
echo '<div class="summary' . $classMod . '">' . substr($row['content'],0,255) . '</div>';
$count++;
}
your code should be like this
CSS
.odd { background: #CCC }
.event { background: #666 }
PHP
$c = true;
while ($row = mysqli_fetch_assoc($dbc)) {
$style = (($c = !$c)?' odd':' even');
echo '<h3 class="title '.$style.'">' . $row['title'] .'</h3>';
echo '<div class="summary '.$style.'">' .substr($row['content'],0,255) . '</div>';
}
Here's a solution with minimal repetition:
$count = 0;
while (($row = mysqli_fetch_assoc($dbc)) && ++$count) {
printf(
'<h3 class="title%1$s">%2$s</h3>'
. '<div class="summary%1$s">%3$s</div>'
, $count % 2 ? "" : "-2"
, $row['title'] // might want to use htmlentities() here...
, substr($row['content'], 0, 255) // and here...
);
}
$i = 0;
while ($row = mysqli_fetch_assoc($dbc)) {
$color =$i % 2;
echo '<h3 class="title-' .$color . '">' . $row['title'] .'</h3>';
echo '<div class="summary">' . substr($row['content'],0,255) . '</div>';
$i++;
}
Your code just displays every result twice. Use a conditional (e.g. an integer or a boolean) to switch between rows (like: if true, then green; if false, then red).
For a boolean you could change the current value like so:
bool = !bool;
Couple of extra points:
You don't (normally) need so many classes. If you have <div class="stripe"> as your container, you can target the items with e.g. .stripe h3 in CSS.
If you target the odd and even items in CSS with .stripe h3, you can then overwrite just the odd items.
In a perfect world, you should keep presentation in the CSS. All browsers but IE7 and below support div:odd to target any odd child of a parent. This may require changing the structure of your HTML slightly. For IE7 and below, I'd add classes with JavaScript instead of PHP. When IE7 is no more then you can just remove the JS.
By the way, you could do this code too:
while ($row = mysqli_fetch_assoc($dbc)) {
echo '<h3 class="title">' . $row['title'] .'</h3>';
echo '<div class="summary">' . substr($row['content'],0,255) . '</div>';
if($row = mysqli_fetch_assoc($dbc)){
echo '<h3 class="title-2">' . $row['title'] .'</h3>';
echo '<div class="summary-2">' . substr($row['content'],0,255) . '</div>';
}
}
IMO, there is no excuse for not delegating this kind of non-critical, presentation layer decoration to client side code.
Just use a library like jQuery and access the odd and even rows like so:
<script>
$(document).ready(function()
{
//for your table rows
$("tr:even").css("background-color", "#F4F4F0");
$("tr:odd").css("background-color", "#EFF1F2");
});
</script>
You'll have us generating font tags next.