count lines in array and split into 2 divs php - javascript

I have a table in my website with 4 columns. I'm using ACF custom field to enter my content.
$string = get_field('projets');
my strings are split into two divs, date_index & texte_index... date_index display the date, and text_index displays the text, so each strings is split when finding a blank space.
like this :
here is the content I enter = 2013-07 PARIS COLLÈGE DE FRANCE
and here is how it is displayed :
<div class="date_index">2013-07</div><div class="texte_index">PARIS COLLÈGE DE FRANCE</div>
it works fine.
then my frist array is split into two column, when first column have 130 lines, then the next lines are displayed in another column.
here is my code :
<div class="columns_projets_1">
<p><?php
$string = get_field('projets');
$array = explode("\n", $string);
for($i = 0; $i <130; $i++){
$dateAndText= explode(' ', $array[$i], 2);
echo '<div class="date_index">'.$dateAndText[0].'</div>';
echo '<div class="texte_index">'.$dateAndText[1].'</div>';
}
?></p>
</div>
<div class="columns_projets_2">
<p><?php
$string = get_field('projets');
$array = explode("\n", $string);
for($i = 130; $i <count($array)-1; $i++){
$dateAndText= explode(' ', $array[$i], 2);
echo '<div class="date_index">'.$dateAndText[0].'</div>';
echo '<div class="texte_index">'.$dateAndText[1].'</div>';
}
?></p>
</div>
then I have a 3rd column, here is the code :
<div class="columns_conferences">
<p><?php
$string = get_field('conferences');
$array = explode("\n", $string);
for($i = 0; $i <300; $i++){
$dateAndText= explode(' ', $array[$i], 2);
echo '<div class="date_index">'.$dateAndText[0].'</div>';
echo '<div class="texte_index">'.$dateAndText[1].'</div>';
}
?></p>
</div>
and my 4th column :
<div class="columns_monographies">
<p><?php
$string = get_field('monographies');
$array = explode("\n", $string);
for($i = 0; $i <300; $i++){
$dateAndText= explode(' ', $array[$i], 2);
echo '<div class="date_index">'.$dateAndText[0].'</div>';
echo '<div class="texte_index">'.$dateAndText[1].'</div>';
}
?></p>
</div>
first of all I would like to delete the condition ( $i <300 )on the 3rd and 4th column, I don't want to have limits in this two columns, but when I try to delete the condition nothing is displayed...
secondly I would like to count the lines in the 3rd column, and this number will be the limit of my first column. so my 1st and 3rd column will have the same lines number.
do you understand what I mean ?
it should be something like that but I can't manage to make it work :
in my 1st column :
for($i = 0; $i <130; $i++){
instead of 130, the number of lines of my 3rd column array.
and for 2nd column ;
for($i = 130; $i
instead of 130, the number of lines of my 3rd column array.
I really hope you can help me with this,
here is a github link :
https://gist.github.com/mattieumoreau/7431037
thanks a lot for your help,

To fix your first issue, use sizeof(array) rather than a specific number, e.g.:
for($i = 0; $i < sizeof($array); $i++){
$dateAndText= explode(' ', $array[$i], 2);
echo '<div class="date_index">'.$dateAndText[0].'</div>';
echo '<div class="texte_index">'.$dateAndText[1].'</div>';
}
Edit:
Your third column would look a bit like this:
<div class="columns_conferences">
<p><?php
$string = get_field('conferences');
$array = explode("\n", $string);
for($i = 0; $i < sizeof($array); $i++){
$dateAndText= explode(' ', $array[$i], 2);
echo '<div class="date_index">'.$dateAndText[0].'</div>';
echo '<div class="texte_index">'.$dateAndText[1].'</div>';
}
?></p>
</div>

There are a few issues going on here.
If you delete the condition, either your for loop is erroring out or it's going on forever (depends on how you're trying to delete it). To get all the records, you want for ($i = 0; $i < count($array); $i += 1) { ...
To limit the length of the first column of 'projets' to the length of 'conferences', you'll need to pick up the data ahead of time, then display it. Here's what I mean:
$projets = explode("\n", get_field('projets'));
$conferences = explode("\n", get_field('conferences'));
$monographies = explode("\n", get_field('monographies'));
// Now we want to limit the length of the first column of projets (col 1) to the
// length of conferences (col 3).
$projets = array_chunk($projets, count($conferences)); // Split the projets into a set of arrays of the right length.
$projets1 = array_shift($projets); // Grab the first one... that's the data for the first column.
$projets2 = array_reduce($projets, 'array_merge', array()); // Merge the remaining arrays into a single array for display.
and then :
function displayDateAndText ($obj)
{
$dateAndText = explode(' ', $obj, 2);
echo "<div class=\"date_index\">{$dateAndText[0]}</div>";
echo "<div class=\"texte_index\">{$dateAndText[1]}</div>";
}
function displayRecords ($records)
{
echo '<p>';
$limit = count($records);
for ($i = 0; $i < $limit; $i += 1)
{
displayDateAndText($records[$i]);
}
echo '</p>';
}
?>
<div class="columns_projets_1">
<?php
displayRecords($projets1);
?>
</div>
<div class="columns_projets_2">
<?php
displayRecords($projets2);
?>
</div>
<div class="conferences">
<?php
displayRecords($conferences);
?>
</div>
<div class="monographies">
<?php
displayRecords($monographies);
?>
</div>

Related

Struggling to increment table column in fives up to a certain number

So basically if $minimum was 30 and $maximum was 40. I wanted the left hand column to from 30 then 35 then 40 while multiplying the values together. I would love some help or even advice.
I added a picture with the result after clicking submit in the html form.
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$costOne = trim($_GET["c1"]);
$costTwo = trim($_GET["c2"]);
$costThree = trim($_GET["c3"]);
$costFour = trim($_GET["c4"]);
$costFive = trim($_GET["c5"]);
$minimum = trim($_GET["min"]);
$maximum = trim($_GET["max"]);
}
echo '<table>';
echo '<tr>';
echo '<th>Cost per person<br>Party size</th>';
echo "<th>$costOne</th>";
echo "<th>$costTwo</th>";
echo "<th>$costThree</th>";
echo "<th>$costFour</th>";
echo "<th>$costFive</th>";
echo '</tr>';
for ($col=$minimum; $col <= $maximum; $col+5) {
echo "<tr>";
echo "<td>$col</td>";
echo "<td>$col*$costOne</td>";
echo "<td>$col*$costTwo</td>";
echo "<td>$col*$costThree</td>";
echo "<td>$col*$costFour</td>";
echo "<td>$col*$costFive</td>";
echo "</tr>";
}
echo '</table>';
?>
Result:
Catering costs

How to echo just few names of a list, in a clean way

I'm using the following code to list the first 7 names of a long list, for each post. The problem is when a certain post contains a list of names inferior to 7, for each missing name til 7, it automatically prints a comma ','
So when names are 7 or more, it correctly shows:
"name1, name2, name3, name4, name5, name6, name7"
While, if for example it contains just 3 names, it will print:
"name1, name2, name3,,,,"
Is there anyway to add something in the code to exclude printing commas in case of names minor to 7?
<?php
$value = get_post_meta($post->ID, 'list_of_names', true);
$value_array = explode(',', $value);
$hrefs = [];
for($i = 0; $i < 7; $i++)
{
$remove_space = str_replace(' ', '-', $value_array[$i]);
$url = esc_url('myblogurl' . $remove_space);
if ('' !== $url)
{
$display = esc_html($value_array[$i]);
$hrefs[] = "<a href='$url'>$display</a>";
}
}
echo implode(",", $hrefs);
?>
I've been trying to add elseif($i < 6) { echo ','; before the end, but it reported me a system error syntax :(
Any advice?
Limit your loop to the size of your $value_array, also maintaining the limit of 7.
for ($i = 0, $count = count($value_array); $i < 7 && $i < $count; $i++)
Another way of coding the same idea:
for ($i = 0, $min = min(7, count($value_array)); $i < $min; $i++)
You have the 'values' in an array, so you could use array functions.
<?php
$values = get_post_meta($post->ID, 'list_of_names', true);
$value_array = explode(',', $values);
$hrefs = [];
foreach (array_slice($value_array,0,7) as $value)
{
$remove_space = str_replace(' ', '-', $value);
$url = esc_url('myblogurl' . $remove_space);
if ('' !== $url)
{
$display = esc_html($value);
$hrefs[] = "<a href='$url'>$display</a>";
}
}
echo implode(",", $hrefs);
?>
See: array_slice()
I would advice to use something other than value as a variable name, if you want others to understand what your code is about.

Unix Timestamp Chart.js with PHP echo

I made a line chart with chart.js. For the values is some PHP script added. The axis only displayed the timestamp numbers. When I use a PHP function for timestamp conversion:
<?php echo date('H:i', $time); ?>
It totally crashes.
This is my code for the PHP time echo. How can I display HH:ii on my X axis of the chart?
<?php
$total = (count($data)) - 1;
if ($total > 100) {
$start = $total - 100;
$end = $total;
}
else {
$start = 0;
$end = $total;
}
for ($x = $start; $x < $end; $x++) {
if ($x % 5 == 0) {
//echo $x; //5th element
$row = $data[$x];
$time = intval($row->{'time'});
echo $time;
} else{
echo ' '; //prints empty for other than 5th element
}
echo ', '; //prints ',' for every element
Fixed it with:
echo '\'' . date('H:i', $time) . '\'';

Grab two values in loop, check box and variable. Only grabbing checkbox? php w screenshot

i make a sql query asking for data(its a text question), i output the (question) with a checkbox to the left of it and an input field underneath it to give point worth to it(like a teacher making an exam) . All in a loop w arrays. It outputs the correctly checked questions but only will assign point values to first three questions if there checked. so if i check q1 q2 and q4 it will output q1 q2 q4 and q1 points q2points. Thats my problem, I only want to be able to select three total questions and assign those questions their points.
php in the html
$sql = " SELECT Question FROM examQuestions";
$result = mysqli_query($dbCon, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<input type="checkbox" name="checkboxvar[]" value="'.$row["Question"].'">'.$row["Question"].'<input placeholder="10" class="form-control" type="number" name="points[]">'."<br />";
}
}
im trying to output the data using this:
$checkboxvar = $_POST['checkboxvar'];
$examName = $_POST['examName'];
$questionWorth = $_POST['points'];
$i=1;
$total = 0;
while ($i < 4) {
$x = $i - 1;
echo $checkboxvar[$x];
echo $questionWorth[$x]."<br />";
$total = $total + $questionWorth[$x];
$i = $i +1;
}
echo $total;
As I told you in the comments try modifying your code like this:
$sql = " SELECT Question FROM examQuestions";
$result = mysqli_query($dbCon, $sql);
$i = 0;
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<input type="checkbox" name="checkboxvar[]" value="'.$i++.'-'.$row["Question"].'">'.$row["Question"].'<input placeholder="10" class="form-control" type="number" name="points[]">'."<br />";
}
}
And then, to have the right points for the correspondig question something like this:
$checkboxvar = $_POST['checkboxvar'];
$examName = $_POST['examName'];
$questionWorth = $_POST['points'];
$i = 0;
$total = 0;
while ($i < 3) {
$question = explode("-", $checkboxvar[$i]);
echo $question[1];
echo $questionWorth[$question[0]]."<br />";
$total += $questionWorth[$question[0]];
$i++;
}
echo $total;
This should do the work.
If i understand your implied question correctly, you will need some client side (javascript) code that keeps track of the number of checked checkboxes. As soon as one checks three boxes all remaining ones and corresponding text boxes are disabled.
for naive vanilla js solution your php could look like this:
$index = 0;
while($row = mysqli_fetch_assoc($result)) {
echo "<label><input class='questions' type='checkbox' name='question_{$index}' value='{$row["Question"]}' on_change='limit_to_three(this);'>{$row["Question"]}<label><br>";
echo "<input class='scores' name='score_{$index}'><br>";
$index++;
}
For modern browsers you would need the following in your javascript :
var selected_count = 0;
function limit_to_three(selected_checkbox) {
if (selected_checkbox.checked) {
selected_count++;
} else {
selected_count--;
}
var limit_reached = (selected_count == 3);
var checkboxes = document.getElementsByClassName('questions');
var scores = document.getElementsByClassName('scores');
for (var i=0; i<checkboxes.length; i++) {
if (!checkboxes[i].checked) {
checkboxes[i].disabled = scores[i].disabled = limit_reached;
}
}
}
Now, upon submit, you can assume that only checked question checkboxes will be submitted, so your php code could be like this:
$total = 0;
$length = strlen('questions_');
foreach ($_POST as $name => $value) {
if (substr($name, 0, $length) == 'questions_') {
$index = substr($name, $length - strlen($name));
echo $_POST[$name];
echo "<br>";
echo $_POST["scores_{$index}"];
$total += $_POST["scores_{$index}"];
}
}
As i said, this is a naive implementation, that sends question texts back and forth. If i were you i would add ID column to your questions table and use it instead of dynamically generated indexes
Then your html could be generated like this:
while($row = mysqli_fetch_assoc($result)) {
echo "<label><input class='questions' type='checkbox' name='question_{$index}' value='{$row["ID"]}' on_change='limit_to_three(this);'>{$row["Question"]}<label><br>";
echo "<input class='scores' name='score_{$row["ID"]}'><br>";
}
and your receiving php could be like this:
$checked = explode(',', $_POST['questions']);
for ($checked as $id) {
$total += $_POST["scores_{$id}"];
}
Also you could retrieve the checked questions by
$sql = "SELECT * FROM Questions WHERE ID IN ({$_POST['questions']})";

Random displays of members images

If I have an array of 50 spots, each spot contains 5 images, I want to randomly display each spot in a table format. One spot per row (5 images) which will be 50 rows in total. Using no database!
<?php
$allImages = array('Image1.jpg','Image2.jpg','Image3.jpg','Image4.jpg');
echo '<table>';
// loop for 12 rows
for($j=0; $j<12; $j++) {
echo '<tr>';
// loop to make 5 columns, 1 column for each image
for($i=0; $i<5; $i++) {
echo '<td>';
$img = $allImages[rand(0,3)];
echo '<img src="'.$img.'">';
echo '</td>';
} echo '</tr>';
}
echo '</table>';
?>
try this:
<?php
$allImages = array('Image1.jpg','Image2.jpg','Image3.jpg','Image4.jpg',
'Image2.jpg','Image3.jpg','Image4.jpg','Image2.jpg',
'Image3.jpg','Image4.jpg','Image2.jpg','Image3.jpg',
'Image4.jpg');
shuffle ( $allImages );
echo '<table><tr>';
for($j=0; $j<count($allImages); $j++) {
echo '<td>';
echo '<img src="'.$allImages[$j].'">';
echo '</td>';
if(($j+1)%5==0) echo "</tr><tr>";
}
echo '</tr></table>';
?>
How about this?
<?php
$allImages = array(
array ('Image01.jpg', 'Image02.jpg', 'Image03.jpg', 'Image04.jpg', 'Image05.jpg'),
array ('Image11.jpg', 'Image12.jpg', 'Image13.jpg', 'Image14.jpg', 'Image15.jpg'),
//.... So on upto 50 slots
array ('Image501.jpg', 'Image502.jpg', 'Image503.jpg', 'Image504.jpg', 'Image505.jpg')
);
$spot_indexes = range(0,2,1); //in your case limit is 50
shuffle($spot_indexes);
foreach($spot_indexes as $index) {
$spot_images = $allImages[$index];
foreach($spot_images as $image) {
echo '<img src ="' .$image. '" height="150px" width="100px" /> ' ;
}
echo '<br>';
}
?>

Categories

Resources