Explode and Set if condition php - php

Array ( [0] => 1 [1] => 2 )
I'm trying to set an if condition based on user permission, the idea is to show menu based on given values, if it is 1, one menu will be displayed and 2 second menu will be displayed, if its both then all values will be displayed. So far for single values i have gotten it right but how to do it for array of values
This is my code
<?php
$userid = $this->phpsession->get("user_id");
$userrole = $this->phpsession->get("user_type");
$query = $this->db->select("role_empid,role_permissions")->from('hw_role')->where('role_empid', $userid)->get()->result();
$data = $query[0]->role_permissions;
if($data == 1){
?>
<li>Add Enquiry</li>
<li>Enquiry List</li>
<?php }else if($data == 2){ ?>
<li>Request For Proposal</li>
<?php } ?>
</ul>

if role_permission contain json object that first convert it into the array like
$data = $query[0]->role_permissions;
$data=json_decode($data);
otherwise direct check the condition for
$data = $query[0]->role_permissions;
if(in_array(1,$data) && in_array(2,$data))
{
}
else if(in_array(1,$data))
{
}
else if(in_array(2,$data))
{
}

If $query[0]->role_permissions is an array that has distinct value, then you can try :
<ul>
<?php for($i = 0; $i<count($data);$i++) {
if($data[$i] == 1){ ?>
<li>Add Enquiry</li>
<li>Enquiry List</li>
<?php }
if($data[$i] == 2){ ?>
<li>Request For Proposal</li>
<?php }} ?>
</ul>

Try This
<?php
if(in_array(1,$data)){
?>
<li>Add Enquiry</li>
<li>Enquiry List</li>
<?php }
if(in_array(2,$data)){
?>
<li>Request For Proposal</li>
<?php } ?>

Related

For loop is making 3600 database requests to load Products. PHP

Problem: One piece (That we can identify currently) is causing a clients product list to call the database over and over again (3600 times) at points when loading a longer list of products.
Code:
<?php foreach ($cats as $cat) :
if (in_array($cat->getId(), [68, 28, 27, 59, 79, 80, 119])) :
$cat_show = Mage::getModel('catalog/category')->load($cat->getId());
$children = $cat_show->getChildrenCategories($cat->getId());
$url1 = $cat_show->getURL();
$showAnyways = in_array(strtolower($cat_show->getName()), ["hats", "juniors", "accessories"]);
if ($cat_show->getShowSidebar() == 1 || $showAnyways) : ?>
<li class="current<?php if ($cat->getId() == $current_cat) { ?> active <?php } ?>">
<?php echo $cat->getName() ?>
<ul>
<?php if ($cat_show->getID() != 68 && $cat_show->getID() != 59) { ?>
<li class="current<?php if ($cat->getId() == $current_cat && $j == 0) {
$j++; ?> active<?php } ?>"><a class="view_all" href="<?php echo $url1 ?>"><?php echo $this->__("View All"); ?></a></li>
<?php } ?>
<?php foreach ($children as $subcat) {
$subcat_show = Mage::getModel('catalog/category')->load($subcat->getId());
if ($subcat_show->getShowSidebar() == 1 || in_array($subcat_show->getID(), [84])) {
$grand_children = Mage::getModel('catalog/category')->getCategories($subcat->getId());
if ($grand_children) {
$cats_displayed = 0;
foreach ($grand_children as $grand_child) {
$grand_child_show = Mage::getModel('catalog/category')->load($grand_child->getId());
if ($grand_child_show->getShowSidebar() == 1) {
$url = Mage::getModel('catalog/category')->load($grand_child_show->getId())->getURL();
?>
<li class="current<?php if ($grand_child->getId() == $current_cat && $j == 0) {
$j++; ?> active<?php } ?>">
<?php echo $grand_child_show->getName() ?>
</li>
<?php $cats_displayed++;
}
}
}
if ($cats_displayed == 0 || !$grand_children) {
$url = Mage::getModel('catalog/category')->load($subcat->getId())->getURL();
?>
<li class="current<?php if ($subcat->getId() == $current_cat && $j == 0) {
$j++; ?> active<?php } ?>">
<?php echo $subcat->getName() ?>
</li>
<?php }
}
} ?>
</ul>
</li>
<?php endif;?>
<?php endif;?>
<?php endforeach; ?>
Can anyone provide me with some pointers on how to make this FAR more efficient and not make so many DB calls.
Should note, I am not an amazing php developer by trade. Main language is python so I am trying to get some advice on the best way to go about fixing this given my less that great knowledge of php itself.
You should never have a database query call inside a for loop. You need to build a query at the start that will get all the data required before the for loop.
Some instant pointers I can see are:
$grand_child_show = Mage::getModel('catalog/category')->load($grand_child->getId());
if ($grand_child_show->getShowSidebar() == 1) {
$url = Mage::getModel('catalog/category')->load($grand_child_show->getId())->getURL();
This is calling the database twice for no reason, you should be able to do this:
$grand_child_show = Mage::getModel('catalog/category')->load($grand_child->getId());
if ($grand_child_show->getShowSidebar() == 1) {
$grand_child_show->getURL();
You should be able to drop all these 'GetModel' functions if at the start of the script you call something like:
$all_grand_children = Mage::getModel('catalog/category')->getAllCategories();
This would return a hash array which you would be able to access relevant items by doing the following inside the for loop:
$grand_children = $all_grand_children[$subcat->getId()];
This would replace
$grand_children = Mage::getModel('catalog/category')->getCategories($subcat->getId());
You should also do a initial call for all of the grand_child and cat_show objects. If you are skilled at SQL you can call just the relevant information by joining the tables in one SQL query.

First while loop stops when second while loop ends

I'm beginner and I'm trying to make a simple navigation menu with a dropdown but the first loop stops when the nested loop is completed. Is there any suggestion? Please be analytic because of my low programming skills.
<?php
function nav_main($dbc, $path) {
$q = "SELECT * FROM navigation ORDER BY position ASC";
$r = mysqli_query($dbc, $q);
while($nav = mysqli_fetch_assoc($r)) {
$nav['slug'] = get_slug($dbc, $nav['url']);
if($nav['parent_id'] == 0) {
?>
<li<?php selected($path['call_parts'][0], $nav['slug'], ' class="active"') ?>><?php echo $nav['label']; ?></li>
<?php
}
elseif ($nav['parent_id'] == 1) {
?>
<li class="dropdown<?php selected($path['call_parts'][0], $nav['slug'], ' active"') ?>"><?php echo $nav['label']; ?><span class="caret"></span>
<ul class="dropdown-menu">
<?php
while($subnav = mysqli_fetch_assoc($r)) {
$subnav['slug'] = get_slug($dbc, $subnav['url']);
if($subnav['parent_id'] == 3) {
?>
<li><?php echo $subnav['label']; ?></li>
<li role="separator" class="divider"></li>
<?php
}
}
?>
</ul>
</li>
<?php
}
}
}
?>
Both your while loops are processing the same result set!
So obviously when the second while loop finishes the resultset is completely consumed and there is nothing left for the outer while look to do but terminate.
This is a precise of what you are doing :-
$q = "SELECT * FROM navigation ORDER BY position ASC";
$r = mysqli_query($dbc, $q);
// first while loop
while($nav = mysqli_fetch_assoc($r)) {
// inner while loop
while($subnav = mysqli_fetch_assoc($r)) {
Both are using $r and therefore regardless of you using a different variable to hold the returned row data the inner loop will consume row 2->end of the same result set as is being processed in the outer while loop

Highlight currenct open menu item using php

I am trying to highlight currently open menu item using PHP.
HTML for my menu items.
<ul class="menu">
<li>Edit Profile</li>
<li>Edit Contact</li>
<li>Edit Facilities</li>
<li>Edit Location</li>
<li>Manage Images</li>
</ul>
This is how I tried it in PHP:
if ($_SERVER['QUERY_STRING']) {
list($queryString) = explode('&',$_SERVER['QUERY_STRING']);
$openPage = $queryString;
list($key, $value) = explode('=',$openPage);
$currentPage = $value;
// Determine what menu item to be highlight:
switch ($currentPage) {
case 'edit-profile':
$class1 = 'class="active"';
break;
case 'edit-contact':
$class2 = 'class="active"';
break;
case 'edit-facilities':
$class3 = 'class="active"';
-----------
// Default is to include the main page.
default:
$class = 'class=""';
break;
} // End of main switch.
} else {
//Determine The Index page
$path = $_SERVER['PHP_SELF'];
$indexPage = basename($path);
$indexPage = basename($path, '.php');
}
This is how I echo these classes in my menus:
<li <?php if(isset($class1)) echo $class1; ?>>Edit Profile</li>
<li <?php if(isset($class2)) echo $class2; ?>>Edit Contact</li>
This is solution is working for me. But my problem is, if I have lot of pages I need to use many class variables in SWITCH case.
Can anybody tell me is there alternative solution for this to minimize my PHP code?
Hope somebody may help me out.
Thank you.
One simple solution would be to store the menu items in a map, and iterate over them:
$menuItems = [
'edit-profile' => [
'url' => 'index.php?p=edit-profile&error=message',
'name' => 'Edit Profile'
],
'edit-contact' => [
'url' => 'index.php?p=edit-contact',
'name' => 'Edit Contacts'
],
...
]
Then iterate over the items.
<ul class="menu">
<?php
foreach($menuItems as $menuItem => $desc) {
// You get $currentPage from the query string
$class = ($currentPage === $menuItem)? 'class="active"': '';
echo '<li '.$class.'>'.$desc['name'].'</li>';
}
?>
</ul>
With this you don't need SWITCH case.
<li <?php if($currentPage=='edit-profile') echo 'class="active"'; ?>>Edit Profile</li>
<li <?php if($currentPage=='edit-contact') echo 'class="active"'; ?>>Edit Contact</li>
You can use array and try like this
if ($_SERVER['QUERY_STRING']) {
list($queryString) = explode('&',$_SERVER['QUERY_STRING']);
$openPage = $queryString;
list($key, $value) = explode('=',$openPage);
$currentPage = $value;
// Determine what menu item to be highlight:
// Store in array, you will be having only one item in array
$class[$currentPage] = 'class="active"';
} else {
//Determine The Index page
$path = $_SERVER['PHP_SELF'];
$indexPage = basename($path);
$indexPage = basename($path, '.php');
}
and the menu can be
<li <?php if(isset($class['edit-profile'])) echo $class['edit-profile']; ?>>Edit Profile</li>
<li <?php if(isset($class['edit-contact'])) echo $class['edit-contact']; ?>>Edit Contact</li>
Note: this not tested, as I have no access to PHP right now.
Rather than doing all this, just take all your menu items in an array and loop over it.
You are sending page parameter with variable.
So, instead have a control over it while sending itself.
Array of page will have page title as key and page url as value.
This way, you do not need separate variables, single variable in loop will serve the job.
<?php
$pages = array(); // Get all page titles and urls in array.
$pages['Edit Profile'] = 'edit-profile&error=message';
$pages['Edit Contact'] = 'edit-contact';
$pages['Edit Facilities'] = 'edit-facilities';
$pages['Edit Location'] = 'edit-location';
$pages['Manage Images'] = 'edit-images';
if (! empty($pages)) {
$current = (isset($_GET['p'])) ? $_GET['p'] : '';
?>
<ul>
<?php
foreach ($pages as $title => $url) {
$active = ($current == $url) ? 'active' : '';
?>
<li><?php echo $title;?></li>
<?php
}
?>
</ul>
<?php
}
?>
Use PHP to generate your own menu structure but for highlighting we can use Jquery.
See example below:
<style>
.active{ background-color:#3F6}
</style>
<ul class="menu">
<li>Home</li>
<li>Edit Profile</li>
<li>Edit Contact</li>
<li>Edit Facilities</li>
<li>Edit Location</li>
<li>Manage Images</li>
</ul>
<script type='text/javascript' src='//code.jquery.com/jquery-1.11.0.js'></script>
<script>
var aurl = window.location.href; // Get the absolute url
$('.menu li a').filter(function() {
return $(this).prop('href') === aurl;
}).parent('li').addClass('active');
</script>

foreach() executing same line again and again

I have a sql field wehre values are like
1,2,3,4,5,6
if fetch those values and explode them below
$amenities = 1,2,3,4,5,6
$amenities_check = explode( "," , $amenities );
Then I run a foreach loop
<?php
$i = 1;
foreach($amenities_check as $amenities_conf)
{
if( $amenities_conf != "" && $amenities_conf == 6)
{
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else
{
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}
if ($i++ == 1) break;
}
?>
Now the problem is that this loop is display the same line 6 times and display the correct class of li when it meets the 6 digit in the data if i apply $i++ it only check the first data in the dataset.
Any help that foreach look for the desired values like 1 2 3 and do the function according to it ..
Thanks
Is this what you are looking for?
<?php
foreach($amenities_check as $amenities_conf) {
if ($amenities_conf == 6) {
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else {
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}
}
?>
EDIT:
<?php
foreach($amenities_check as $amenities_conf) {
if ($amenities_conf == 6) {
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
}
?>
<li class="not_amen">Smoking Allowed</li>
or like the guys above said, use in_array().
<?php
if (in_array("6", $amenities_check)) {
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
?>
<li class="not_amen">Smoking Allowed</li>
From the comments, what you actually want to know is if there is a 6 anywhere in the array, so you don't want to be outputting anything at all in the loop. The simplest approach is to use the fairly self-explanatory in_array function; as simple as this:
if( in_array('6', $amenities_conf) )
{
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else
{
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}
Alternatively, break apart your logic from your display by looping through the database result once and preparing structured data based on it. The below is probably over-kill for this example, but shows a general approach:
// While retrieving data from the DB
$amenity_names = array(
1 => 'pets',
// ...
6 => 'smoking'
);
$included_amenities = array();
$amenities_check = explode( "," , $amenities );
foreach ( $amenities_check as $amenity )
{
$name = $amenity_names[$amenity];
$included_amenities[$name] = true;
}
// In the View / template code
if( $included_amenities[['smoking'] )
{
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else
{
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}

change value of variable based on conditions php

I have a class name that should change based on certain conditions but either my syntax or my logic seems to be incorrect as it doesn't work:
if ( $hometeam && ($homescore > $awayscore) || $awayteam && ($awayscore > $homescore)){
$status= 'win';
}
if ( $hometeam && ($homescore < $awayscore) || $awayteam && ($awayscore < $homescore)) {
$status= 'lose';
}
if ($homescore == $awayscore) {
$status= 'draw';
}
My elements each have a class="<?php echo $status; ?>" and I want them to be styled differently depending on the value of $status. I didn't use else if because I didn't want it to apply the value and stop but it looks like that is what is happening.
Edit: Some clarification:
<ul class="match group">
<li>
<ul class="team1 <?php echo $status; ?>">
<li class="teamname"><h2><?php echo $homename; ?></h2></li>
<li class="teamscore"><?php echo $homescore; ?></li>
</ul>
</li>
<li>
<ul class="team2 <?php echo $status; ?>">
<li class="teamname"><h2><?php echo $awayname?></h2></li>
<li class="teamscore"><?php echo $awayscore?></li>
</ul>
</li>
<li><ul class="matchinfo">
<li><button>Get Report</button></li>
</ul>
</li>
</ul>
By your logic, there are only two possible outcomes for the value of $status: 'lose' or 'draw'.
Why is this? Basic logic says that unless there is a tie, a game will always have a winner. Your if statement lines up with this. Either $homescore > $awayscore or $homescore < $awayscore (or there is a tie). So in the event of a non-tie, one of the sides of your first if will evaluate to true, and therefore the entire condition will be true since || needs only one truthy. So unless there is a tie, $status will be set to 'win'.
Moving on, basic logic will also tell us that a game always has a loser unless there is a tie. Again, your code conforms to this. In the event of a non-tie, one of the score will be less than the other and therefore your second if will evaluate to true like the first did. Now $status = 'lose'.
Now if there is a tie, $status would equal 'draw', but otherwise $status will always be 'lose' because if the game has a winner, it also has a loser and $status is set to 'lose' after it is set to 'win'.
What you need here is a variable for the winner, loser, and for a draw. Like so:
$winner = '';
$loser = '';
$draw = false;
if($homescore > $awayscore) {
$winner = 'home';
$loser = 'away';
} else if($homescore < $awayscore) {
$winner = 'away';
$loser = 'home';
} else if($homescore === $awayscore) {
$draw = true;
}
(Codepad Demo)
This code also makes use of else if, because you don't need to evaluate the other conditions if you've determined who won and lost.
You need to group your conditions better.
if ( ($hometeam && ($homescore > $awayscore)) || ($awayteam && ($awayscore > $homescore)))
{
$status= 'win';
}
else if ( ($hometeam && ($homescore < $awayscore)) || ($awayteam && ($awayscore < $homescore)))
{
$status= 'lose';
}
else
{
$status= 'draw';
}
if ($homescore > $awayscore) {
$homestatus = 'win';
$awaystatus = 'lose';
} else if ($homescore < $awayscore) {
$homestatus = 'lose';
$awaystatus = 'win';
} else {
$homestatus = 'draw';
$awaystatus = 'draw';
}
<ul class="match group">
<li>
<ul class="team1 <?php echo $homestatus; ?>">
<li class="teamname"><h2><?php echo $homename; ?></h2></li>
<li class="teamscore"><?php echo $homescore; ?></li>
</ul>
</li>
<li>
<ul class="team2 <?php echo $awaystatus; ?>">
<li class="teamname"><h2><?php echo $awayname?></h2></li>
<li class="teamscore"><?php echo $awayscore?></li>
</ul>
</li>
<li><ul class="matchinfo">
<li><button>Get Report</button></li>
</ul>
</li>
</ul>

Categories