I have a PHP object that I am looping over, I know 2 things are definate with this object, I will never need to loop more than 12 times (1-12) and I will also always have to loop at least once.
My problem comes when the object is longer than 6 items, as if it is longer than 6 items I need to split the results into 2 <ol> and for the live of me I cannot figure out a nice way to do this?
Here is my attempt,
<?php $count = 1; ?>
<?php if(is_object($active_projects)) : ?>
<div class="col_1">
<?php if($count < 2) : ?>
<strong>Active projects</strong> View All
<?php endif; ?>
<ol <?php echo ($count > 1 ? " class='no-header'" : ""); ?>>
<?php foreach($active_projects as $project) : ?>
<li><?php echo $project->project_name; ?></li>
<?php $count ++; ?>
<?php endforeach; ?>
</ol>
</div>
<?php endif; ?>
Now my attempt displays all the results in one list, how can if there are more than 6 items in the object, split the loop in 2 so that I output 2 <div class="col_1"> with a list of 6 items in each?
Try this:
<?php
//create an object with 12 items
$obj = new stdClass();
for($i = 1; $i <= 12; $i++)
{
$project = "project_$i";
$obj->{$project} = new stdClass();
$obj->{$project}->name = "Project $i";
}
function wrapInLi($projectName)
{
return "<li>$projectName</li>\n";
}
function wrapInOl($arrayOfLi)
{
$returnString = "<ol>\n";
foreach ($arrayOfLi as $li)
{
$returnString .= $li;
}
return $returnString . "</ol>\n";
}
/*
* The classname is adjustable, just in case
*/
function wrapInDiv($ol, $class)
{
return "<div class='$class'>\n$ol</div>\n";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
$arrayOfLi = array();
foreach($obj as $project)
{
//fill an array with list-items
$arrayOfLi[] = wrapInLi($project->name);
//six list-items? wrap it
if(count($arrayOfLi) === 6)
{
//wrap in unordered list
$ol = wrapInOl($arrayOfLi);
//wrap in div and echo
echo wrapInDiv($ol, 'col_1');
//reset array
$arrayOfLi = array();
}
}
?>
</body>
</html>
Related
Problem:
So when I login, a user can go to the browse.php to add images to the favorites.php, and the photos will appear on that page.
When I log out and log back in, the images are gone (not saved).
Question:
How do I save it after I logout so on next login I get to see the favorite'd images from that particular user using cookies or other methods (can't use database because I'm not allowed to)?
My favorites page
<?php
session_start();
require_once 'favoritesfunction.php';
if (isset($_GET["fileName"])) {
$fileName = $_GET["fileName"];
addToFavorites($fileName);
}
?>
<!DOCTYPE html>
<html>
<head>
<?php
$title = "Travel Photos - View Favorites";
?>
<link rel="stylesheet" href="viewfavorites.css" />
</head>
<body>
<main class="container">
<h1 class="favheader">Favorites</h1>
<div class="content">
<?php
if (isset($_SESSION['favorites']) && isset($_SESSION['email'])) {
$favorites = $_SESSION['favorites'];
if (count($favorites) > 0) {
?> <ul class="ul-favorite"> <?php
foreach ($favorites as $f) {
echo '<img class="displayPic" src="https://storage.googleapis.com/assignment1_web2/square150/' . $f . '">';
}
?>
</ul>
<p id="removeall"><button class="button"><span><a target="" href="services/removefavorites.php?remove=all">Remove All</a></span></button></p>
<?php
}
} else {
?>
<div class="nofavorites">
<p>No favorites found.</p>
</div>
<?php
}
?>
</div>
</main>
</body>
<script type="text/javascript" src="main.js"></script>
</html>
My add to favorites function php
<?php
function addToFavorites($fileName)
{
//Checks if the session favorites exists
if (isset($_SESSION['favorites'])) {
$favorites = $_SESSION['favorites'];
} else {
$favorites = array();
$_SESSION['favorites'] = $favorites;
}
// add item to favourites
$item = $fileName;
$match = false;
//Loop below checks for duplicates
$i = 0;
while ($i < count($favorites)) {
if ($favorites[$i] == $item) {
$favorites[$i] = $item;
$match = true;
}
$i++;
}
//if match equals false, that means its not in the favorites list of the user
//so it is added to the user's favorites array
if ($match == false) {
$favorites[] = $item;
}
$_SESSION['favorites'] = $favorites;
$_SESSION['favorites'] = $favorites;
}
My approach:
I tried doing something like setting $name = $_SESSION['email'] and $value="<img src=...>" then setcookie($name, $value) and then if(isset($_COOKIE[$value])) echo $value
I know this is totally wrong, I tried looking everywhere online to try to solve this, if I could get some help that would be great thanks!
I am having a problem in adding the product as a variable with variations. I am trying to add accessories on every product page but its working for simple product and is creating the problem in a variable or with variations
i tried to solve this
//this variable code is not working//
<?php if($currentProduct->get_type() == "variable"){ ?>
var varRules = $(".variations_form").data('product_variations');
<?php foreach($currentProduct->get_attributes() as $k=>$v){ ?>
var attribute_<?= getVar($k) ?> = $("select[name=attribute_<?= $k ?>]").val();
<?php } ?>
$.each(varRules,function(){
<?php
$cond = [];
foreach($currentProduct->get_attributes() as $k=>$v){
$cond[] = '(this.attributes["attribute_'.$k. '"]=='. 'attribute_'.getVar($k).' || this.attributes["attribute_'.$k. '"]=="")';
} ?>
if(<?=implode(" && ", $cond)?>){
total = this.display_price;
}
});
//not even this grouped one//
<?php } else if($currentProduct->get_type() == "grouped"){ ?>
var total = 0;
<?php foreach($currentProduct->get_children() as $k=>$id){ ?>
total += $("[name='quantity[<?= $id ?>]']").val() * <?= getPrice(wc_get_product($id)); ?>;
<?php } ?>
<?php } else { ?>
total = parseFloat(<?= getPrice($currentProduct) ?>);
<?php } ?>
i want it to work for variable products
As it seems that you are using php inside some jQuery code, there are some errors like:
Your php opening tags should all be always like <?php but not like <?=
When you want to display something like a variable from php in jQuery, dont forget echo
Dont forget missing ; before your closing php tags.
I have revisited your code, but nobody can test it as it's an extract with missing things and the context is also missing from your question.
<?php if($currentProduct->get_type() == "variable"){ ?>
var varRules = $(".variations_form").data('product_variations');
<?php foreach($currentProduct->get_attributes() as $k => $v){ ?>
var attribute_<?php echo getVar($k); ?> = $("select[name=attribute_<?php echo $k; ?>]").val();
<?php } ?>
$.each(varRules,function(){
<?php
$cond = [];
foreach($currentProduct->get_attributes() as $k=>$v){
$cond[] = '(this.attributes["attribute_'.$k.'"]=='. 'attribute_'.getVar($k).' || this.attributes["attribute_'.$k.'"]=="")';
} ?>
if(<?php echo implode(" && ", $cond) ?>){
total = this.display_price;
}
});
//not even this grouped one//
<?php } else if($currentProduct->get_type() == "grouped"){ ?>
var total = 0;
<?php foreach($currentProduct->get_children() as $k=>$id){ ?>
total += $("[name='quantity[<?php echo $id; ?>]']").val() * <?php echo getPrice(wc_get_product($id)); ?>;
<?php } ?>
<?php } else { ?>
total = parseFloat(<?php echo getPrice($currentProduct); ?>);
<?php } ?>
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>
Consider a table for example
using these table I just wanted to print a table like these by adding rowspan to item id 1002.
Here is my PHP code
$temp_val = '';
$counter = 1;
$sql_sel = mysqli_query($con,"select * from item_table");
while($res_sel = mysqli_fetch_array($sql_sel)){
if($temp_val == $res_sel['item_id']){
$counter++;
echo "<tr></tr>";
}
else{
echo "<tr><td rowspan='".$counter."'>".$res_sel['item_id']."</td></tr>";
}
$temp_val = $res_sel['item_id'];
}
echo "</table>";
it's not correct, it's adding rowspan to item id 1003
You can't do like this because when you create the first row then you have to decide how much will this column can span so you have to get the count of the similar ids first to achieve it. I am just giving you and idea how it can work with and array like you database provides.
<?php
// Array comming from database
$databaseValues = [
[
'item_id'=>'1001',
'item_color'=>'black',
],
[
'item_id'=>'1002',
'item_color'=>'blue',
],
[
'item_id'=>'1002',
'item_color'=>'green',
],
[
'item_id'=>'1003',
'item_color'=>'red',
]
];
// Creating an array as per the need for the table
$arrayForTable = [];
foreach ($databaseValues as $databaseValue) {
$temp = [];
$temp['item_color'] = $databaseValue['item_color'];
if(!isset($arrayForTable[$databaseValue['item_id']])){
$arrayForTable[$databaseValue['item_id']] = [];
}
$arrayForTable[$databaseValue['item_id']][] = $temp;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<table border="1">
<?php foreach ($arrayForTable as $id=>$values) :
foreach ($values as $key=>$value) :?>
<tr>
<?php if($key == 0) :?>
<td rowspan="<?= count($values)?>"><?= $id?></td>
<?php endif;?>
<td><?= $value['item_color']?></td>
</tr>
<?php endforeach;
endforeach; ?>
</table>
</body>
</html>
Hope this will be helpfull for you
You should switch the code inside else and if statement
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 -->