Im attempting to create a simple list out of some elements I stole from a more complex list of rows etc., I just need list out the values in single row separated by commas.
<?php foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
echo nbf_common::nb_strlen($document_item->product_code);
}
;} ?>
;} ?>
<?php } ?>
The Result I get follows "3 ;} ?> 3 ;} ?> 4 ;} ?> 3 ;} ?> "
Thanks in advance
Micah
try this
<?php
foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
echo nbf_common::nb_strlen($document_item->product_code);
}
}
}
?>
Fore more detail PHP Tags
Change the #9, #10, remove #11 line. What you're doing is printing characters: ;} ?>
and are syntactically wrong. This is proper:
<?php foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
echo nbf_common::nb_strlen($document_item->product_code);
}
} // here
} // here
?>
Also for the "comma separated" part, put required values in a variable and echo it at the end.
Could be like this:
<?php
$string = '';
foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
$string .= nbf_common::nb_strlen($document_item->product_code).',';
}
}
}
echo rtrim($string, ','); // remove the last comma
?>
or use a temp array to glue them at the end:
<?php
$lines = array();
foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
$lines[] = nbf_common::nb_strlen($document_item->product_code);
}
}
}
echo implode(',', $lines); // bind them with comma
?>
I'm not sure why you have all those extra ?>. The pattern is:
<?php
// PHP code goes here
?>
i.e. every <?php has a matching ?>; no more, no less.1
1. Other than the case that #Mihai points out in the comment below...
To understand the php tags you might want to think that you are in an HTML file and you are intrerrupting the HTML flow with
When writing PHP only files (classes, interfaces, traits lists of functions and similar grouping of application code with no templating) it is advisable to open at the very first character in the file and not end it at all.
When writing template files however it is advisable to use php's alternate syntax:
<?php if($x): ?>
<?php elseif($y): ?>
<?php else: ?>
<?php endif; ?>
Instead of the standard:
<?php if($x) { ?>
<?php } else if($y) { ?>
<?php } else { ?>
<?php } ?>
Related
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 } ?>
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.
I have this code where if something then display a link, else display another link. the if and else are php code, and the links are html as you will know, but I was wondering how do you make it so it will not give me any errors, how do I combine php with html?
<?php foreach ($user_socs as $user_soc) {
if ($soca == $user_soc) {
Leave Society;
} else {
Join Society;
}
This might help you. This one is from the basics of PHP:
<?php foreach ($user_socs as $user_soc) {
if ($soca == $user_soc) {
echo "<a href='file.php' class='socbuttons'>Leave Society</a>";
} else {
echo "<a href='anotherfile.php' class='socbuttons'>Join Society</a>";
}
}
?>
Remember PHP should be surrounded by <?php ?>. Simply end the "PHP part" and then start it again when you finished your HTML.
<?php foreach ($user_socs as $user_soc) {
if ($soca == $user_soc) {
?> Leave Society <?
} else {
?> Join Society<?
}
Also, you can write HTML in echo statement, but you should escape some special characters like " to not interfere with the php code itself.
<?php foreach ($user_socs as $user_soc) {
if ($soca == $user_soc) {
echo "Leave Society";
} else {
echo "Join Society";
}
See http://php.net/manual/en/function.echo.php to more information.
Try this
<?php foreach ($user_socs as $user_soc) {
if ($soca == $user_soc) { ?>
Leave Society;
<?php } else { ?>
Join Society;
<?php }
Use alternate syntax:
<?php
$aUserSocs = array( 'link1', 'link2', 'link3' );
$soca = 'link2';
$iCountUserSocs = count( $aUserSocs );
for( $i = 0; $i < $iCountUserSocs; ++$i ):
?>
<?php if( $soca == $aUserSocs[ $i ] ): ?>
Leave Society;
<?php else: ?>
Join Society;
<?php endif; ?>
<?php endfor; ?>
I'm using multiple if statements to check a containing div, and output an image based on the container name. The code was working fine until I add a final "else" or change the if's out to elseif and I can't figure out why that's happening. When I try to add the else or elseif, the entire page fails to load. Any idea why this is happening?
<?php
if($viewMore['container_type'] == 'Large IMG' || $viewMore['container_type'] == 'Gallery') {
$photoSql = "SELECT * FROM `cms_uploads` WHERE (`tableName`='site_content' AND `recordNum` = '".$viewMore['num']."' AND `fieldname`= 'large_images') ORDER BY `order`";
$photoResult = $database->query($photoSql);
$photoResultNum = $database->num_rows($photoResult);
$photoArray = array();
while($photoResultRow = $database->fetch_array($photoResult)) {
array_push($photoArray, $photoResultRow);
}
$large = 0; foreach ($photoArray as $photo => $upload): if (++$large == 2) break;
?>
<img class="features" src="<?php echo $upload['urlPath'] ?>">
<?php endforeach ?>
<?php } ?>
<?php
elseif($viewMore['container_type'] == 'Medium IMG') {
$photoSql = "SELECT * FROM `cms_uploads` WHERE (`tableName`='site_content' AND `recordNum` = '".$viewMore['num']."' AND `fieldname`= 'small_images') ORDER BY `order`";
$photoResult = $database->query($photoSql);
$photoResultNum = $database->num_rows($photoResult);
$photoArray = array();
while($photoResultRow = $database->fetch_array($photoResult)) {
array_push($photoArray, $photoResultRow);
}
$medium = 0; foreach ($photoArray as $photo => $upload): if (++$medium == 2) break;
?>
<img class="features" src="<?php echo $upload['urlPath'] ?>">
<?php endforeach; ?>
<?php } ?>
<?php else { ?> SOMETHING HERE <?php } ?>
EDIT:
Other notes
I've tried wrapping the break; in brackets because I thought that piece following the count might be messing with something. Also removing the counter altogether or adding a semi colon after the endforeach didn't help.
Whenever you close your PHP block, think about all the text/HTML outside it being put into PHP's echo function.
What gave me alarm bells was this part:
<?php } ?>
<?php else { ?> ...
What that translates into is:
if (...) {
} echo "[whitespace]"; else {
}
which clearly makes your else block unexpected.
You should not close the PHP block between your closing if and opening else, i.e. do this instead:
...
} else {
...
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
}