Incorporating extra loop into random selection? - php

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 -->

Related

PHP Output my XML feed in a random order

I have my XML output working fine but it's in latest date order. What would be cool is if I could get it in a random order. I've tried using shuffle and I just can't get it working (nothing seems to happen).
Here's an example of the code I'm using to build my XML. The output is HTML with PHP to insert variables.
// Build the Feed
$feed = "http://www.reviewswebsite.com/api/consumer-reviews/?username=" . $userName . "&format=xml&reviews_per_page=20&page=" . $pageNumber;
$xml = simplexml_load_file($feed);
for($i = 0; $i < $numberOfForLoops; $i++)
{
$reviewer_name = $xml->reviews->review[$i]->reviewer_name;
$date_of_work = date('l, d m Y' , strtotime($xml->reviews->review[$i]->date_of_work));
$average_reviewer_rating = (float)$xml->reviews->review[$i]->average_rating;
..
?>
<div><?php echo $reviewer_name; ?></div>
...
<?php ;} ?>
#The Fourth Bird helped me by passing this link: Randomize SimpleXML object results
The end result I created for Trust-A-Trader reviews which I built into a Joomla! module was. I'll try to release the module for free on the Joomla! Extensions Directory (JED).
End code was
$feed = "http://www.trustatrader.com/api/consumer-reviews/?username=" . $userName . "&format=xml&reviews_per_page=20&page=" . $pageNumber;
$xml = simplexml_load_file($feed);
// Count Reviews, if total number of reviews is less than the total shown on page set in module then show the lesser amount to avoid an error.
$totalNumberOfReviews = count($xml->reviews->review);
$numberOfForLoops = $totalNumberOfReviews;
if ($totalNumberOfReviews > $numberOfReviews) {
$numberOfForLoops = $numberOfReviews;
}
// If the module sets the order to random then shuffle array, or else do in latest first date order.
if ($params->get('Order') == 0) {
foreach($xml->reviews->review as $val)
$array[]= $val;
shuffle($array);
}
// Loop through the reviews and output them.
foreach($array as $val)
{
$i = 0;
if ($i < $numberOfForLoops)
{
?>
<div class="mod_trust_a_trader_reviews--review g-grid" itemscope itemtype="http://schema.org/Review" itemprop="review" >
<div class="review g-block size-100" itemprop="reviewBody">
<?php echo $val->comments; ?>
</div>
<div class="authorBlock g-grid size-100">
<span class="author g-block size-100" itemprop="author">
<?php echo $val->reviewer_name; ?>
</span>
</div>
<div class="score g-block size-100 g-grid">
<div class="g-block size-100">
<?php starRatingImage($val->average_rating); ?>
</div>
<div class="g-block size-100 reviewRating">
<?php echo '(<span itemprop="reviewRating">' . $val->average_rating . '</span>)'; ?>
</div>
</div>
</div>
<?php
}
$i++;
}
?>

PHP Html in while loop

I have two html / css content. One of them floating left, the other one floating right.
I wanna pull data from my database, then putting them in a order. Left, right, left, right.
$services = pullservices();
while ($service = mysqli_fetch_object($services)){
for ($i=1; $i<=mysqli_num_rows($services); $i++) {
if ($i % 2 == 0): ?>
Left HTML Content
<?php else: ?>
Right HTML Content
<?php
endif;
}
}
?>
I have 6 items on db. But that code keeps looping one data for 6 times and it doing that for all the data on db.
That is the pullservices function.
function pullservices()
{
global $connect;
$products_query_string = "SELECT
id,
title_tr AS title,
text_tr,
short_text_tr,
image,
icon
FROM services WHERE status = 1 ORDER BY ordering , title_tr";
$products_query_run = mysqli_query($connect, $products_query_string);
return $products_query_run;
You can do this simply by using a flag.
(pseudo code):
$services = pullservices();
$flag=0;
while ($service = mysqli_fetch_object($services)){
if ($flag==0): ?>
Left HTML Content
<?php $flag=1; ?>
<?php else: ?>
Right HTML Content
<?php $flag=0; ?>
<?php
endif;
}
?>
One way you might be able to do this would be to split the data from the recordset and call it later in the html like this
$services = pullservices();
$i=0;
$data=array(
'left' =>array(),
'right' =>array()
);
while( $rs = mysqli_fetch_object( $services ) ){
$key = $i % 2 == 0 ? 'right' : 'left';
/* add the real data rather than placeholder data */
$data[ $key ][]=sprintf('%s HTML Content %d', ucfirst( $key ), $i );
$i++;
}
<div id='left'>
<?php
echo implode( PHP_EOL, $data['left'] );
?>
</div>
<div id='right'>
<?php
echo implode( PHP_EOL, $data['right'] );
?>
</div>

show div tag in php statement

I am now working on a WordPress theme base with the Advanced Custom Fields plugin, And I want to show a <div> tag when the if statement is true. Here is my code:
<?php
$rows = get_field('classification');
$sort = get_sub_field('sort');
$row_count = count($rows);
for ($i = 1; $i <= $row_count; $i++)?>
<?php if ( $i==1 || $i%5==0) { ?>
<div class="bor"></div>
<h3 style="text-align:center">
<?php echo $sort; ?>
<a id="browser"></a></h3>
<div class="bor"></div>
<?php } ?>
or something like that
<?php
$rows = get_field('classification');
$fenlei = get_sub_field('fenlei');
$row_count = count($rows);
for ($i = 1; $i <= $row_count; $i++)?>
<?php if ( $i==1 || $i%5==0) { ?>
echo '<div class="bor"></div>';
echo '<h3 style="text-align:center">';
<?php echo $fenlei; ?>
echo '<a id="browser"></a></h3>';
<div class="bor"></div>
<?php } ?>
But the content of the div tag doesn't show.
Any reply is appreciated!Thank you very much.
some of your echo statement are out php tags. use this:
<?php
$rows = get_field('classification');
$fenlei = get_sub_field('fenlei');
$row_count = count($rows);
for ($i = 1; $i <= $row_count; $i++){
if ( $i==1 || $i%5==0) {
echo "<div class='bor'></div>
<h3 style='text-align:center'>".$fenlei."
<a id='browser'></a></h3>
<div class='bor'></div>";
}
}
?>
If you wanted to show the html in php, i suggest you use the below code.
<?php
$rows = get_field('classification');
$fenlei = get_sub_field('fenlei');
$row_count = count($rows);
for($i = 1; $i <= $row_count; $i++){
if ( $i==1 || $i%5==0) {
echo '>div class="bor"<>/div<';
echo '>h3 style="text-align:center"<';
echo $fenlei;
echo '>a id="browser"<>/a<>/h3<';
echo '>div class="bor"<>/div<';
}
}
?>
I'm guessing you're using an ACF Pro Repeater field. in this case you need to use the_row() which will set the sub-field's correct content. look at this edited example from the Docs:
<?php
// check if the repeater field has rows of data
if( have_rows('repeater_field_name') ):
// loop through the rows of data
while ( have_rows('repeater_field_name') ) : the_row();
// display a sub field value
the_sub_field('sub_field_name');
endwhile;
endif;
?>
so, I think your code should look more like:
<?php
if(have_rows('classification')):
while (have_rows('classification') ) : the_row();
// Your Code...
endwhile;
endif;
?>
And, I've learned recently you need to count the rows outside the while loop. othewise it won't catch the rows amount.

serial number for faq displayed from admin

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 ?

Codeigniter table Join then Display Tags Problem

I have a problem that concerns blog posts and displaying the tag words from another table.
I seem to be able to pull the info out of the tables fine, however when I try to display the posts and the tags, I get one tag per post. In other words if I have 7 tags for a post, I get 7 iteration's of that post each with one tag instead of 1 post with 7 tags.
My Controller ( do have a question about the $this->db->get(posts, tags) is that correct
$this->db->order_by('posts.id', 'DESC');
$where = "publish";
$this->db->where('status', $where);
$this->db->join('tags', 'tags.post_id = posts.id');
$this->db->limit('7');
$query = $this->db->get('posts', 'tags');
if($query->result())
$data = array();
{
$data['blog'] = $query->result();
}
$data['title'] = 'LemonRose';
$data['content'] = 'home/home_content';
$this->load->view('template1', $data);
The view.
$limit = 5; // how many posts should we show in full?
$i = 1; // count
foreach ($blog as $row):
$permalink = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].$_SERVER['QUERY_STRING'];
$url = CompressURL ("$permalink");
$description = $row->title . $row->post;
$twittermsg = substr($description, 0, 110);
$twittermsg .= "...more " . $url;
if ($i < $limit) // we are under our limit
{ ?>
<div class="titlebox">
<div class="title"><? echo ucwords($row->title); ?></div>
<span><? echo $row->date, nbs(10), $row->author; ?></span>
</div>
<div class="clear"></div>
<? $str = str_word_count($row->post, 0);
if ($str >= 500) {
$row->post = html_entity_decode($row->post);
$row->post = $this->typography->auto_typography($row->post); // display?>
<div class="split"> <? echo $row->post = word_limiter($row->post, 480); ?>
<div class="tags"><? echo $row->tag; ?></div>*** These 3 lines seem to be where I am confused and getting the wrong display
<p><h3>More <?php echo anchor("main/blog_view/$row->id", ucwords($row->title)); ?> </h3></p>
<p>Trackback URL: <? echo base_url() . "trackbacks/track/$row->id"; ?></p>
<!-- tweet me -->
<?echo anchor("http://twitter.com/home?status=$twittermsg", 'Tweet'); ?>
This is my first attempt with join and I have very little experience getting the display with implode, if that is the right way to go.
Thank you in advance.
Try
<div class="tags"><? echo implode(', ', $row->tag); ?></div>
and remove the 2 rows before this one.

Categories