Create list per 4 records [duplicate] - php

This question already has answers here:
display data in multiple columns
(3 answers)
Closed 8 years ago.
I am trying to create multi-list of records with 4 records per list without knowing how many records there are. However, I cannot figure out how to handle the math. I manually typed in $n == 5 || $n == 9 etc knowing it is stipud and cannot exactly solve the problem. Can anyone help me how to handle that. Also, the lists underneath works well only if the total number of records cannot be evenly divided by 4. If it can, it will create a blank list at the end.
$query = "SELECT * FROM `table` WHERE `field` = $whatever";
if ($result = $con->query($query)){
$n = 1
$row_cnt = $result->num_rows;
$total_lists = round($row_cnt / 4, 0);
$current_list = 1;
echo "<ul>List $current_list of $total_lists";
while ($row = $result->fetch_assoc()) {
echo "<li>$row['something']</li>";
if ($n == 5 || $n == 9 || $n == 13 || $n == 17 || $n == 21 || $n ==25 || $n ==29 || $n == 33 || $n == 37 || $n == 41 || $n == 45 || $n == 49 || $n == 53 || $n == 57 || $n == 61 || $n == 65 || $n == 69 || $n == 73 || $n == 77){
echo "</ul>";
$current_list = $current_list + 1;
echo "<ul>List $current_list of $total_lists";
}
$n = $n + 1;
}
echo "</ul>";
}
Thanks in advance for the help. :)
SOLVED:
$query = "SELECT * FROM `table` WHERE `field` = $whatever";
if ($result = $con->query($query)){
$n = 0
$row_cnt = $result->num_rows;
$total_lists = ceil($row_cnt / 4);
$current_list = 1;
echo "<ul>List $current_list of $total_lists";
while ($row = $result->fetch_assoc()) {
$n++;
echo "<li>$row['something']</li>";
if ($row_cnt > 4) {
if ($n % 4 === 0) {
echo "</ul>";
$current_list = $current_list + 1;
echo "<ul>List $current_list of $total_lists";
}
}
}
echo "</ul>";
}

You're actually not too far off track from what you might want to be doing, you just need to use one additional tool to accomplish it: the % or modulus operator.
The modulus operator will return the remainder of division problem:
$x = 5 % 2; // 1
Looking at your logic, your action needs to be taken when your incrementer ($n) minus 1 divided by 4 would have a remainder of 0:
if (($n - 1) % 4 === 0)
{
//your <ul> insertion could go here.
}
Here's a link to the PHP manual page discussing mathematical operators:
http://us1.php.net/manual/en/language.operators.arithmetic.php

Alternatively, you could use a simple array_chunk() on your db results. Provide the proper grouping (in this case by four's) to it and them loop them thru foreach. Consider this example:
// dummy data (values from db)
$values_from_db = array(
array('id' => 1, 'something' => 'list1'),
array('id' => 2, 'something' => 'list2'),
array('id' => 3, 'something' => 'list3'),
array('id' => 4, 'something' => 'list4'),
array('id' => 5, 'something' => 'list5'),
array('id' => 6, 'something' => 'list6'),
array('id' => 7, 'something' => 'list7'),
array('id' => 8, 'something' => 'list8'),
array('id' => 9, 'something' => 'list9'),
);
$values_from_db = array_chunk($values_from_db, 4); // group them by four's
?>
<?php foreach($values_from_db as $key => $value): ?>
<ul style="list-style-type: none;">
<?php foreach($value as $index => $element): ?>
<li><?php echo $element['id'].'.'.$element['something']; ?></li>
<?php endforeach; ?>
</ul>
<?php endforeach; ?>

Related

How to make 5 conditional with only 1 if 2 else if 1 else?

I have a certain conditional like below.
>80 category A
71-80 category AB
51-70 category B
41-50 category BC
<40 category C
I need to make a code that meet above condition. But only with
1 if
2 else if
1 else
I figured out that i need to set the default category value, but it still does not meet the expected result
$category= "C";
$value = "10";
if ($value > 80) {
$category = "A";
}else if ($value <= 70 AND $value > 50) {
$category = "B";
}else if ($value <= 80 AND $value > 70) {
$category = "AB";
}else{
$category = "BC";
}
echo $category;
i want to make output like this
90 = A
72 = AB
55 = B
45 = BC
10 = C
but my code show below
90 = A
72 = AB
55 = B
45 = BC
10 = BC
If the point is to limit the keywords if, else and else if, you can use ternary operator in the last else.
function getCat($val)
{
$cat = '';
if ($val >= 81) {
$cat = 'A';
} else if ($val >= 71 && $val <= 80) {
$cat = 'AB';
} else if ($val >= 51 && $val <= 70) {
$cat = 'B';
} else {
$cat = $val < 40 ? 'C' : 'BC';
}
return $cat;
}
Here's a demo
There's one issue though. If the value is 40, this would give it BC, but you never wrote any rule for that number so it is what it is
How about this, only one if statement is used and you said that you would like an array solution in one of the comments:
$categories = [
'80' => 'A',
'71' => 'AB',
'51' => 'B',
'41' => 'BC',
];
$value = "10";
$category= "C";
foreach ($categories as $minVal => $cat) {
if ($value >= $minVal) {
$category = $cat;
break;
}
}
echo $category;
You can do it something like this:
<?php
$value = 81;
$edge_cases = ['C','A'];
$category = '';
if($value > 40 && $value <= 50){
$category = 'BC';
}else if($value > 50 && $value <= 70){
$category = 'B';
}else if($value > 70 && $value <= 80){
$category = 'AB';
}else{
$quotient = intval($value / 80);
$index = abs(intval($quotient / (($quotient - 1) | 1)));
$category = $edge_cases[$index];
}
echo $category;
Demo: https://3v4l.org/78S4p
Although it's always better to make division between a range and get the quotient as only 2 options of either 0 or 1, here is another way of doing the same thing.
In the above code, we make sure that we always get the index as 1 if $quotient > 0, else we make it 0 itself.
Try this one.
if ($value < 40 ) {
$category = "C";
}else if ($value <= 50 && $value != 40) {
$category = "BC";
}else if ($value <= 70 ) {
$category = "B";
}else{
$category = $value > 80 ? "A" : "AB";
}
If you're allowed to use a ternary you can do this :
if ($value > 80) {
$category = 'A';
} else if ($value > 70) {
$category = 'AB';
} else if ($value > 50) {
$category = 'B';
} else {
$category = $value > 40 ? 'BC' : 'C';
}
#u_mulder thought the same ^^
Sorry - I think I completely missed the point, but I thought I would answer more for entertainment and as a complete alternative to the problem. I present the no if solution...
$category = ['C', 'C', 'C', 'C', 'BC', 'B', 'B', 'AB', 'A', 'A' ];
echo $category[min(max(floor(($value-1)/10),0),9)];
I ended up adding the min() and max() to ensure it didn't get errors with -1 or 101.
If people think my answer should be deleted, then let me know as I am not answering the original problem :-/
Here's one way that should satisfy the conditions. The else obviously isn't really necessary.
$category = '';
if ($value > 70 && !($category .= 'A')) {
} elseif ($value > 40 && $value < 81 && !($category .='B')) {
} elseif ($value < 51 && $category .= 'C') {
} else {}

PHP Variable declaration not working in Laravel 5.4

I have the following code in a Laravel 5.4 Blade view:
#php($strVal = $character->Strength)
#php($strMod = 0)
<?php
if ($strVal == 10 || 11) {
$strMod = 0;
} elseif ($strVal == 12 || 13) {
$strMod = 1;
} elseif ($strVal == 14) {
$strMod = 2;
} else {
$strMod = 2;
}
?>
It takes data from a MySQL table.
$strVal is an int from the table. The code creates a var called $strMod and goes through a number of if/elseif statements to see what it will be equal to.
It's shown on a webpage as follows:
<div class="huge charMod">+{{$strMod}}</div>
My issue is that it displays as "+0" no matter what strVar equals. strVar is working fine, I can pull it from the DB and display it via {{ $strVal }} but strMod refuses to take a value other than 0.
$strVal == 10 || 11 will always return true
Because that's not how comparisons work in PHP. The == operator has a higher precedence than || operator, so it will be performed first.
It means that $strVal == 10 || 11 gets turned into false || 11 .. which is true.
Instead of that code, I would recommend:
$map = [
10 => 0,
11 => 0,
12 => 1,
13 => 1,
// you dont actually need 14, because default value is aready 2
];
$result = 2;
if (array_key_exists($strVal, $map)) {
$result = $map[$strVal];
}
$strVal = $result;
Or, if you are using PHP 7.0+ it all can actually be written as:
$map = [10 => 0, 11 => 0, 12 => 1, 13 => 1];
$strVal = $map[$strVal] ?? 2;
You need to change your if checks to
if ($strVal == 10 || $strVal == 11) {
$strMod = 0;
} elseif ($strVal == 12 || $strVal == 13) {
$strMod = 1;
} elseif ($strVal == 14) {
$strMod = 2;
} else {
$strMod = 2;
}
if ($strVal == 10 || 11) will always return true. If you want to check two values you need to specify that by using the variable == value again as in the example above.

Summerize all fields if exists from database

I have different fields in the database and im fetching their values.
Now what I would like to do is subract a number if certain field exists in database.
Here is my code:
<?php
$percent_profile_image = 40;
$percent_cover_image = 20;
$percent_profiletext = 10;
$percent_travelintext = 10;
$percent_sparetimetext = 10;
$percent_gouttext = 10;
$avatar_status_num;
$cover_status_num;
$profiletext = $display_profile['profile_text_approved'];
$sparetimetext = $display_profile['spare_time_text_approved'];
$travelintext = $display_profile['traveling_text_approved'];
$gouttext = $display_profile['go_out_text_approved'];
if($avatar_status_num == 2) { echo $percent_profile_image; } + if($avatar_status_num == 2) { echo $percent_profile_image; }
?>
Now I know my if code is wrong. What I would like to do if example $avatar_status_num = 2 i would like to print out 40. if $cover_status_num = 2 I would like to substract these to numbers so. 40 + 20. So it should only print out the number and substract it if the value from DB is nr2.
I hope you understand my question :)
Cheerz
Use an extra variable to sum your values.
$sum = 0;
if (isset($someValue) && $someValue == 2) {
$sum += 40;
}
if (isset($someOtherValue) && $someOtherValue == 2) {
$sum += 20;
}
Or if you wanna do this dynamically in your code:
$percent = array(
'profile_image' => 40,
'cover_image' => 20,
'profile_text_approved' => 10,
'traveling_text_approved' => 10,
'spare_time_text_approved' => 10,
'go_out_text_approved' => 10,
);
$sum = 0;
foreach ($display_profile as $key => $value) {
if (array_key_exists($key, $percent) && $value == 2) {
$sum += $percent[$key];
}
}
Note In this case the $percent key names should be the same as the $display_profile key names.

Php break the ul li

I am showing images in php in ul list. I want to show 5 li in my ul then 2 li and after that again 5 li.I am using this code but it is showing 5 li every row.
<?php
$data = array(1,2,3,4,5,6,7,8,9,10,11,12);
$break_after = 5;
$counter = 0;
$totalNumber = count($data);
foreach ($data as $item)
{
if ($counter % $break_after == 0)
{
echo '<ul>';
}
echo '<li>'.$item.'</li>';
if ($counter % $break_after == ($break_after-1) || $counter == $totalNumber-1) {
echo '</ul>';
}
++$counter;
}
dfff
fdfddf
fdfd
ffd
fdfd
fddf
dfdf
fddf
dfdf
dfdf
fddf
fddf
fdfd
fddf
fddf
fdfd
fddf
Hope this solution might help you :
When you want a break after 5,2,5 Y not take that an array array(5,2,5) instead of just break_after=5. break_after=5 will breake the ul at every 5 intervals. I have some change in logic for you :
$data = array(1,2,3,4,5,6,7,8,9,10,11,12);
$break_after = array(5,2,5);
$counter = 0;
$break_key=0;
$totalNumber = count($data);
foreach ($data as $item){
if ($counter % $break_after[$break_key] == 0){
echo '<ul>';
}
echo '<li>'.$item.'</li>';
if ($counter % $break_after[$break_key] == ($break_after[$break_key]-1) || $counter == $totalNumber-1) {
echo '</ul>';
++$break_key;
$counter = 0;
}else{
++$counter;
}
}
Output for same is :
<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>
<ul><li>6</li><li>7</li></ul>
<ul><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li></ul>
To achieve what you want use the following:
<?php
$data = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22);
$total = count($data);
foreach ($data as $index => $item)
{
if ($index == 0 || $index == 5 || $index == 7 || ($index > 8 && ($index - 2) % 5 == 0))
{
echo '<ul>';
}
echo '<li>'.$item.'</li>';
if ($index == 4 || $index == 6 || $index == $total - 1 || ($index > 6 && ($index - 2) % 5 == 4)) {
echo '</ul>';
}
}
Pretty much the same answer as varunsinghal and Vivek Tankaria, but refactored to separate the logic and the view:
<?php
$pattern = [5, 2, 5, 5];
$data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];
if (count($data) < array_sum($pattern)) {
throw new Exception('Please provide at least the same amount of data as lines required in the pattern');
}
?>
<?php foreach ($pattern as $limit): ?>
<ul>
<?php for ($i = 0; $i < $limit; $i++): ?>
<li><?= $data[$i]; ?></li>
<?php endfor; ?>
</ul>
<?php endforeach; ?>
For multiple values in array.
$data = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36);
$break_after = array(5,2,5);
$counter = 0;
$break_key=0;
$totalNumber = count($data);
foreach ($data as $item){
if ($counter % $break_after[$break_key] == 0){
echo '<ul>';
}
echo '<li>'.$item.'</li>';
if ($counter % $break_after[$break_key] == ($break_after[$break_key]-1)) {
echo '</ul>';
++$break_key;
if(count($break_after)==($break_key)){
$break_key=0;
}
$counter = 0;
}else{
++$counter;
}
}
?>
You can try this logic
<?php
$data = array(1,2,3,4,5,6,7,8,9,10,11,12);
$breakPoint=4;
$ct=1;
echo '<ul>';
foreach($data as $k=>$v){
echo '<li>'.$v.'</li>';
if($breakPoint == $k && $ct==1){
$breakPoint=$breakPoint+2;
$ct=2;
echo '</ul><br/><ul>';
}elseIf($breakPoint == $k && $ct==2){
$breakPoint=$breakPoint+5;
$ct=1;
echo '</ul><br/><ul>';
}
}
echo '</ul>';
?>
Output:
1
2
3
4
5
6
7
8
9
10
11
12
First break is at 5 so $i will be 4 then 2 elements more so $i will be 6. After this the break is required after every 5 elements, so we have 5+2+5 = 12 elements which gives $i=11 So similarly other break points will be 11 16 21 26 31 36 and so on.
<ul>
<?php
$i=0;
foreach($data as $item){
echo '<li>'.$item.'</li>';
if($i==4 || $i==6 || $i==11 || $i==16 || $i==21 || $i==26){
echo '</ul><ul>';
}
$i++;
}
?>
</ul>

Need a little help for algorithm

Right now I have a set of if and elseif to set the height of the div
<?php
if($num == 0){echo 'height:0px;';}
elseif($num > 0 && $num < 10) {echo 'height:3px;';}
elseif($num >= 10 && $num < 22) {echo 'height:7px;';}
elseif($num >= 22 && $num < 45) {echo 'height:16px;';}
elseif($num >= 45 && $num < 50) {echo 'height:33px;';}
elseif($num >= 50 && $num < 67) {echo 'height:36px;';}
elseif($num >= 67 && $num < 79) {echo 'height:48px;';}
elseif($num >= 79 && $num < 88) {echo 'height:56px;';}
elseif($num >= 88) {echo 'height:72px;';}
?>
The problem is that this is copyed 5 times for 5 different divs and think there is better way to do it
Like so :
<?php
function divHeight($maxNum,$number)
{
if($number == 0)
{
echo 'height:0px;' ;
}
elseif($number >= $maxNum)
{
echo 'height:72px;' ;
}
else
{
//here were the algorithm have to be
}
}
?>
I will call it like <?php divHeight(88,$number);?>
The max height of div is 72, now how to calculate the height?
// Edit : This is so simple :X :X but is too late and i havent sleept so
$newHeight = floor($number * 72 / 100);
echo $newHeight;
function mapNumToHeight($num) {
// Max $num => height for that num
$heightMap = array(
0 => 0,
9 => 3,
21 => 7,
44 => 16,
49 => 33,
66 => 36,
78 => 48,
87 => 56,
88 => 72
);
// Store the keys into an array that we can search
$keys = array_keys($heightMap);
rsort($keys);
// We want to find the smallest key that is greater than or equal to $num.
$best_match = $keys[0];
foreach($keys as $key) {
if($key >= $num) {
$best_match = $key;
}
}
return 'height:' . $heightMap[$best_match] . 'px;';
}
mapNumToHeight(3); // height:3px;
mapNumToHeight(33); // height:16px;
mapNumToHeight(87); // height:56px;
mapNumToHeight(88); // height:72px;
mapNumToHeight(1000); // height:72px;

Categories