while ($row = mysql_fetch_array($result)) {
<h3> <?php echo $row['ideaTitle']; ?> </h3>
<blockquote>
<p>
<em>
<?php echo $row['feedback']; ?>
</em>
</p>
</blockquote>
<?php } ?>
Here's my working code. I want to attempt to find when $row['ideaTitle'] is new, but I'm not sure how to do it. I thought about setting a temp variable w/ the title name, but I feel like there needs to be a simpler solution.
Using a temporary variable is pretty much the way to go, I would say -- that's what I do in this kind of situation.
And it generally translates to this kind of code :
$previousTitle = null;
while ($row = mysql_fetch_array($result)) {
if ($row['ideaTitle'] != $previousTitle) {
// do something when the current line
// is the first with the current title
}
// work with $row
// Store the current title to the temporary variable,
// to be able to do the comparison on next iteration
$previousTitle = $row['ideaTitle'];
}
There is no other way than to use a temporary variable. But instead of using a single last value string, try a count map:
if (#$seen_titles[ $row["ideaTitle"] ]++ == 0) {
print "new title";
}
This trick works, because the counting up ++ is in effect done after the comparison. It needs an # error suppression however for the redundant notices here.
Imo this is quite a simple solution. However, you could also preprocess the data and create a title => feedbacks map:
$feedbacks = array();
while (($row = mysql_fetch_array($result))) {
if(!array_key_exists($row['ideaTitle'], $feedbacks) {
$feedbacks[$row['ideaTitle']] = array();
}
$feedbacks[$row['ideaTitle']][] = $row['feedback'];
}
And then create the output:
<?php foreach($feedbacks as $title => $fbs): ?>
<h3> <?php echo $title; ?> </h3>
<?php foreach($fbs as $fb): ?>
<blockquote>
<p>
<em><?php echo $fb ?></em>
</p>
</blockquote>
<?php endforeach; ?>
<?php endforeach; ?>
Keep a track of previously encountered titles in a key value array.
$prevTitles = array();
while ($row = mysql_fetch_array($result)) {
if($prevTitles[$row['ideaTitle']] == true)
continue;
$prevTitles[$row['ideaTitle']] = true;
<h3> <?php echo $row['ideaTitle']; ?> </h3>
<blockquote>
<p>
<em>
<?php echo $row['feedback']; ?>
</em>
</p>
</blockquote>
<?php } ?>
Related
I would like to list (upto) six of the remaining assignments due for the acedemic year onto a webpage.
The data for the remaining assignments comes from a mysql db.
When there are six or more assignments left, the webpage displays the info correctly.
If there are less than six left, then i get a undefined offset error (and i understand why).
Basically, i am trying to programmatically ignore the offset error.
I've tried looking and the following:
try/catches in the php.
tried using (in the foreach loop)
if($row['name'] == null){$row['name'] = "";}
etc.
index.php
include('getdata.php');
$nextAssArray0 = getNextAssessments($courseInfoArray[0], 0);
$nextAssArray1 = getNextAssessments($courseInfoArray[0], 1);
$nextAssArray2 = getNextAssessments($courseInfoArray[0], 2);
$nextAssArray3 = getNextAssessments($courseInfoArray[0], 3);
$nextAssArray4 = getNextAssessments($courseInfoArray[0], 4);
$nextAssArray5 = getNextAssessments($courseInfoArray[0], 5);
<div class="col-sm-4">
<h3>You have <?php echo '' ?> assignments left</h3>
<p>Assignment: <?php echo $nextAssArray0[0]; ?> is due on <?php echo $nextAssArray0[1]; ?></p>
<p>Assignment: <?php echo $nextAssArray1[0]; ?> is due on <?php echo $nextAssArray1[1]; ?></p>
<p>Assignment: <?php echo $nextAssArray2[0]; ?> is due on <?php echo $nextAssArray2[1]; ?></p>
<p>Assignment: <?php echo $nextAssArray3[0]; ?> is due on <?php echo $nextAssArray3[1]; ?></p>
<p>Assignment: <?php echo $nextAssArray4[0]; ?> is due on <?php echo $nextAssArray4[1]; ?></p>
<p>Assignment: <?php echo $nextAssArray5[0]; ?> is due on <?php echo $nextAssArray5[1]; ?>
</p>
</div>
getdata.php
function getNextAssessments($courseID, $offset)
{
try
{
include('dbconn.php');
$array = array();
$stm = $conn->prepare("CALL getUpcomingAssignments(:courseID, :offset)");
$stm->bindParam(':courseID', $courseID);
$stm->bindParam(':offset', $offset);
$stm->execute();
foreach ($stm->fetchALL() as $row)
{
array_push($array, $row['name']);
array_push($array, $row['due_date']);
array_push($array, $row['tem']);
}
}
catch (Exception $e)
{
$array = array('','','');
}
return $array;
}
I am after the following functionality:
1) if there is only three assignments left - then only three display.
2) if there is ten assignments left - then only six are displayed.
3) if there are no assignments left - then nothing is displayed in those
First of all, it is not a good idea to make SQL query for every database record. Remove limit from query, and put all your assesments in array. Then do something like this:
<h3>You have <?php echo count($assesments) ?> assignments left</h3>
<?php
foreach($assesments as $assesment){
echo "<p>Assignment: {$assesment[0]} is due on {$assesment[1]} ?></p>"
}
?>
Also I would recommend changing your code so you have array like $assesment['dueDate'] instead of $assesment[1].
Is there a way to check if a subArea contains blocks before outputting markup when using the Area Splitter add-on?
Have been trying stuff like this but don't understand how to make it work sorry:
<?php
defined('C5_EXECUTE') or die("Access Denied.");
$c = Page::getCurrentPage();
$this->controller->setArea($this->area);
?>
<div class="box">
<? if (($this->controller->subArea()->getTotalBlocksInArea($c) != 0) || ($c->isEditMode())) : ?>
<div class="box-header">
<?php $this->controller->subArea(); ?>
</div>
<? endif; ?>
<? if (($this->controller->subArea()->getTotalBlocksInArea($c) != 0) || ($c->isEditMode())) : ?>
<div class="box-footer">
<?php $this->controller->subArea(); ?>
</div>
<? endif; ?>
</div>
Any pointers in the right direction would be much appreciated.
Cheers
Ben
Not sure about the "area splitter" addon... I believe that's a really old thing that has been supplanted by the native "Area Layouts" in the core (which were added way back in 5.4 I believe).
If you're talking about the native "area layouts" functionality, though, then I have some code in the free Page List Teasers addon that does this:
$aHandle = 'Main'; //<--CHANGE THIS ACCORDINGLY
$c = Page::getCurrentPage();
//Get blocks inside "Area Layouts"...
$layout_blocks = array();
$area = new Area($aHandle);
$layouts = $area->getAreaLayouts($c); //returns empty array if no layouts
foreach ($layouts as $layout) {
$maxCell = $layout->getMaxCellNumber();
for ($i=1; $i<=$maxCell; $i++) {
$cellAreaHandle = $layout->getCellAreaHandle($i);
$cellBlocks = $c->getBlocks($cellAreaHandle);
$layout_blocks = array_merge($layout_blocks, $cellBlocks);
}
}
//Get non-area-layout blocks...
$nonlayout_blocks = $c->getBlocks($aHandle); //Returns blocks in the order they're on the page
//Combine the two sets of blocks
$blocks = array_merge($layout_blocks, $nonlayout_blocks);
Hopefully you can take that code and modify it to achieve what you want (e.g calling count() on the layout_blocks array or the combined array, depending on which you want).
I'm using multiple if statements to check a containing div, and output an image based on the container name. The code was working fine until I add a final "else" or change the if's out to elseif and I can't figure out why that's happening. When I try to add the else or elseif, the entire page fails to load. Any idea why this is happening?
<?php
if($viewMore['container_type'] == 'Large IMG' || $viewMore['container_type'] == 'Gallery') {
$photoSql = "SELECT * FROM `cms_uploads` WHERE (`tableName`='site_content' AND `recordNum` = '".$viewMore['num']."' AND `fieldname`= 'large_images') ORDER BY `order`";
$photoResult = $database->query($photoSql);
$photoResultNum = $database->num_rows($photoResult);
$photoArray = array();
while($photoResultRow = $database->fetch_array($photoResult)) {
array_push($photoArray, $photoResultRow);
}
$large = 0; foreach ($photoArray as $photo => $upload): if (++$large == 2) break;
?>
<img class="features" src="<?php echo $upload['urlPath'] ?>">
<?php endforeach ?>
<?php } ?>
<?php
elseif($viewMore['container_type'] == 'Medium IMG') {
$photoSql = "SELECT * FROM `cms_uploads` WHERE (`tableName`='site_content' AND `recordNum` = '".$viewMore['num']."' AND `fieldname`= 'small_images') ORDER BY `order`";
$photoResult = $database->query($photoSql);
$photoResultNum = $database->num_rows($photoResult);
$photoArray = array();
while($photoResultRow = $database->fetch_array($photoResult)) {
array_push($photoArray, $photoResultRow);
}
$medium = 0; foreach ($photoArray as $photo => $upload): if (++$medium == 2) break;
?>
<img class="features" src="<?php echo $upload['urlPath'] ?>">
<?php endforeach; ?>
<?php } ?>
<?php else { ?> SOMETHING HERE <?php } ?>
EDIT:
Other notes
I've tried wrapping the break; in brackets because I thought that piece following the count might be messing with something. Also removing the counter altogether or adding a semi colon after the endforeach didn't help.
Whenever you close your PHP block, think about all the text/HTML outside it being put into PHP's echo function.
What gave me alarm bells was this part:
<?php } ?>
<?php else { ?> ...
What that translates into is:
if (...) {
} echo "[whitespace]"; else {
}
which clearly makes your else block unexpected.
You should not close the PHP block between your closing if and opening else, i.e. do this instead:
...
} else {
...
I have the code below that is selecting a random set of questions from Wordpress.
<?php
$rows = get_field('step_by_step_test');
$row_count = count($rows);
$rand_rows = array();
$questions = get_field('select_number_of_questions');
for ($i = 0; $i < min($row_count, $questions); $i++) {
$r = rand(0, $row_count - 1);
while (array_search($r, $rand_rows) !== false) {
$r = rand(0, $row_count - 1);
}
$rand_rows[] = $r;
echo $rows[$r]['question'];
}
?>
I want to incorporate a bit of extra code (below), how can I make sure it's selecting the same random question?
<?php if(get_sub_field('answer_options')): ?>
<?php while(has_sub_field('answer_options')): ?>
<?php echo the_sub_field('answer'); ?>
<?php endwhile; ?>
<?php endif; ?>
Why dont you change your approach slightly?
<?php
$rows = get_field('step_by_step_test'); // Get the test
$question_count = get_field('select_number_of_questions'); // Get the number of questions
$rows = shuffle($rows); // Randomize your questions
$rows = array_slice($rows, $question_count); // Now set the array to only contain the number of questions you wanted
foreach ($rows as $row) {
echo $row['question']; // Show the question
if(get_sub_field('answer_options', $row['id'])) {
while(has_sub_field('answer_options', $row['id'])) {
echo the_sub_field('answer');
}
}
}
?>
I made the assumption that you can alter "get_sub_field" to include the ID of the question, so you can then include the ID in your "where" field of "answer_options". This will allow you to link the question.
I think that what you need is to set up the whole thing in a loop. query by custom field
Or you could store the ids of the questions you got above, an then, below, query for the answers for those specific posts.
Here's how I randomized my WordPress slider using the Advanced Custom Fields plugin + Royal Slider with a modified version of TheSwiftExchange's code above
<div id="full-width-slider" class="royalSlider heroSlider rsMinW">
<?php
/*
* Slider Repeater field shuffled
* http://stackoverflow.com/questions/12563116/incorporating-extra-loop-into-random-selection
*/
$rows = get_field('slider');
// For Debugging:
// echo "<pre>";
// var_dump($rows);
// echo "</pre>";
$quotes = get_field('slide_text'); // Get the number of images
shuffle($rows); // Randomize your slides
foreach ($rows as $row) {
$slideImageID = $row['slide_image'];
$slideImage = wp_get_attachment_image_src( $slideImageID, 'full' );
$slideText = $row['slide_text'];
?>
<div class="rsContent">
<div class="royalCaption">
<div class="royalCaptionInner">
<div class="infoBlock">
<?php if(!empty($slideText)) {
echo $slideText;
}; ?>
</div>
</div>
</div>
<img src="<?php echo $slideImage[0]; ?>" class="" />
</div><!-- /.rsContent -->
<?php } // end foreach ?>
</div><!-- /slider-wrap -->
I am using the following code for display questions and answers from admin.
<?php
$select_faq = "Select `intFaqid`, `varQuestion`,`varAnswer` FROM `tbl_faq`";
$selectfaq_result = mysql_query($select_faq);
$select_faqnum = mysql_num_rows($selectfaq_result);
if($selectfaq_result > 0)
{
while($fetch_faq = mysql_fetch_array($selectfaq_result))
{
$faqid = $fetch_faq['intFaqid'];
$fquestion = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varQuestion']))));
$fanswer = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varAnswer']))));
?>
<h3><?php echo $fquestion; ?></h3>
<p><?php echo $fanswer; ?></p>
<?php
}
}
?>
I need to display the question number before the question. I used the following code for display the question number.
<?php
$questionno = 1;
$numberlimit = $select_faqnum;
while($questionno<=$numberlimit)
{
echo $questionno;
$questionno++;
}
?>
But i doesn't know how to display the question number before the question by combining both the codes. I need the output should display the question with question number. How can i do that?
Am I missing something? I am not sure why you would make it so complex.
Since your recordset is already determining the number of rows, why not just do this:
if($selectfaq_result > 0)
{
//initialise your variable
$question_number = 0;
while($fetch_faq = mysql_fetch_array($selectfaq_result))
{
//increment your variable
$question_number++;
$faqid = $fetch_faq['intFaqid'];
$fquestion = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varQuestion']))));
$fanswer = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varAnswer']))));
?>
//concatenate the string to include the variable.
//Don't forget to leave a space after it so it looks pretty
<h3><?php echo $question_number . ": " . $fquestion; ?></h3>
<p><?php echo $fanswer; ?></p>
<?php
}
Your line number will finish when you run out of records
<?php
$select_faq = "Select `intFaqid`, `varQuestion`,`varAnswer` FROM `tbl_faq`";
$selectfaq_result = mysql_query($select_faq);
$select_faqnum = mysql_num_rows($selectfaq_result);
if($select_faqnum > 0)
{
$question_number = 0;
while($fetch_faq = mysql_fetch_array($selectfaq_result))
{
$question_number++;
$faqid = $fetch_faq['intFaqid'];
$fquestion = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varQuestion']))));
$fanswer = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varAnswer']))));
?>
<h3><?php echo "$question_number. $fquestion"; ?></h3>
<p><?php echo $fanswer; ?></p>
<?php
}
}
?>
is that what you are looking for ?