Magento, getProductUrl() returning same url - php

I'm working on showing x amount of related products on the shopping cart page.
Here is my current code
$cart = Mage::getModel('checkout/cart')->getQuote();
$c = count($cart);
if($c != 0) {
$c = $c - 1;
$rand = rand(0, $c);
$i = 0;
foreach ($cart->getAllItems() as $item) {
if($i == $c) {
$productId = $item->getProduct()->getId();
$model = Mage::getModel('catalog/product');
$product = $model->load($productId);
$allRelatedProductIds = $product->getRelatedProductIds();
$rc = count($allRelatedProductIds) - 1;
$rand = rand(0, $rc);
$relatedProduct = $model->load($allRelatedProductIds[$rand]);
echo "<div class='page-title'><h1>Maybe you would like to try one of these</h1></div>";
foreach($allRelatedProductIds as $prod) {
$p = $model->load($prod);
echo "<a href='".$p->getProductUrl()."'>";
echo "<div style='float:left; font-size:1.3em; width:33%; line-height:1.25; font-family:\"karlaregular\"'>";
echo "<img src='".Mage::helper('catalog/image')->init($p, 'small_image')->resize(300,300) ."' style='width:100%; height:100%;'>";
echo "<h2 class='product-name' style='text-align:center;'>".$p->getName()."</h2>";
echo "<div class='pricebox' style='text-align:center;'><span class='regular-price'><span class='price'>£".number_format($p->getPrice(), 2)."</span></span></div>";
echo "</div>";
echo "</a>";
}
}
$i++;
}
}
This almost works 100% problem is that the $p->getProductUrl() is only being populated by the first product in the loop and gives the wrong url to all sequential products.
I cannot see any issues with the above and would someone to take a look.
Thanks

Please try below code
$cart = Mage::getModel('checkout/cart')->getQuote();
$c = count($cart);
if($c != 0) {
$c = $c - 1;
$rand = rand(0, $c);
$i = 0;
foreach ($cart->getAllItems() as $item) {
if($i == $c) {
$productId = $item->getProduct()->getId();
$model = Mage::getModel('catalog/product');
$product = $model->load($productId);
$allRelatedProductIds = $product->getRelatedProductIds();
$rc = count($allRelatedProductIds) - 1;
$rand = rand(0, $rc);
$relatedProduct = $model->load($allRelatedProductIds[$rand]);
echo "<div class='page-title'><h1>Maybe you would like to try one of these</h1></div>";
foreach($allRelatedProductIds as $prod) {
$p = Mage::getModel("catalog/product")->load($prod);
echo "<a href='".$p->getProductUrl()."'>";
echo "<div style='float:left; font-size:1.3em; width:33%; line-height:1.25; font-family:\"karlaregular\"'>";
echo "<img src='".Mage::helper('catalog/image')->init($p, 'small_image')->resize(300,300) ."' style='width:100%; height:100%;'>";
echo "<h2 class='product-name' style='text-align:center;'>".$p->getName()."</h2>";
echo "<div class='pricebox' style='text-align:center;'><span class='regular-price'><span class='price'>£".number_format($p->getPrice(), 2)."</span></span></div>";
echo "</div>";
echo "</a>";
}
}
$i++;
}
}

Related

how to make a table row contents to break lline? [duplicate]

I have the following code:
for($i=0; $i<count($gallery);$i++)
{
$temp = array();
$temp = $gallery[$i];
echo "<img src='". $temp->path . "' />";
}
Now this code prints the content in one row. I want to print only 3 per row and then create new row and print another 3 and so on. How can this be done?
appreciate the support :)
EDIT: error
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 5
Filename: views/profile.php
Line Number: 105
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: views/profile.php
Line Number: 106
You can do
$n = 3;
echo "<table><tr>";
for($i=0; $i<count($gallery);$i++){
$temp = array();
$temp = $gallery[$i];
echo "<td><img src='". $temp->path . "' /></td>";
if($i % $n ==0 && $i!=0 ){
echo "</tr><tr>";
}
}
echo '</tr></table>';
Edit:
If you want to do it the "right" way - by building the syntactically correct HTML, you need to do:
$n = 3;
echo "<table><tr>";
$gallery_count = count($gallery);
for($i=0; $i<$gallery_count; $i++){
$temp = array();
$temp = $gallery[$i];
echo "<td><img src='". $temp->path . "' /></td>";
if($i != 0){
if($i % $n == 0 && $i != $gallery_count-1){
echo "</tr><tr>";
}
else{
echo ""; //if it is the last in the loop - do not echo
}
}
}
//example - if the last 2 `td`s are missing:
$padding_tds = $gallery_count % $n;
if($padding_tds != 0 ){
$k = 0;
while($k < $padding_tds){
echo "<td> </td>";
}
}
echo '</tr></table>';
You just need to a modulus that checks how many have been printed - any multiple of 3 will add a break.
$x=0;
for($i=0; $i<count($gallery);$i++)
{
$x++;
$temp = array();
$temp = $gallery[$i];
echo "<img src='". $temp->path . "' />";
if (($x%3)==0) { echo "<br />"; }
}
I just redid it with tables, it's much neater, because each thing will be formatted to look correctly.
It's kind of messy because I just added a little if statement to release the tables.
<table>
<?php
$number_per_row = 3;
for($i=0; $i<count($gallery);$i++)
{
$temp = array();
$temp = $gallery[$i];
if(($i % $number_per_row) == 0) {
echo "<tr>";
}
?>
<td><?php echo "<img src='". $temp->path . "' />"; ?></td>
<?php
if(($i % $number_per_row) == $number_per_row - 1) {
echo "</tr>";
}
}
?>
</table>
$n = 3;
echo "<table>";
echo "<tr>";
for($i=0; $i<count($gallery);$i++){
if(($i % n ==0) && ($i != 0)){
echo "</tr><tr>";
}
$temp = array();
$temp = $gallery[$i];
echo "<td><img src='". $temp->path . "' /></td>";
}
echo "</tr>";
echo '</table>';``

Make new table after reaching a certain row count

I created a code that converts characters to binary and make table cells black/white corresponding to the ones and zeros. This is my code:
$str_splt = str_split($text);
echo "<table>";
for ($a=0;$a < count($str_splt);$a++) {
$bits = array(128,64,32,16,8,4,2,1);
$store = array(0,0,0,0,0,0,0,0);
$inp = ord($str_splt[$a]);
for ($x=0;$x < count($bits);$x++) {
if ($bits[$x] <= $inp) {
$inp = $inp - $bits[$x];
$store[$x] = 1;
} else {
$store[$x] = 0;
}
};
$store_rvs = array_reverse($store);
echo "<tr>";
for ($b=0;$b < count($store_rvs);$b++) {
if ($store_rvs[$b] == '1') {
echo "<td id=\"blk\"></td>";
}
else {
echo "<td></td>";
}
}
echo "</tr>";
}
echo "</table>";
Its output looks like this ($text = "ABCDEFGH"):
As you can see it's 8x8 table. I want to add the next set of bytes to the side of that table like this:
Each 8x8 table is a group. The two images above is group 1 and group 2:
I want to display the tables like this but I can't find the solution.
I did it in this way. Ignore my css if you are fine with yours. I replaced the id tag with class because each id should be defined once only.
echo "<html><head>";
echo "<style type='text/css'>";
echo " table, td { padding:0px; margin:0px; }";
echo " td.cell { width:15px; height:15px; }";
echo " td.blk { background-color:black; }";
echo " td.wht { background-color:yellow; }";
echo "</style>";
echo "</head><body>";
$text = "ABCDEFGH";
$text.= "ABCDEFGH";
echo "<table><tr><td><table>";
for($a=0; $a<strlen($text); $a++) {
$chr = substr($text,$a,1);
$bits = array(128,64,32,16,8,4,2,1);
$store = array(0,0,0,0,0,0,0,0);
$inp = ord($chr);
for($x=0; $x<count($bits); $x++) {
if($bits[$x] <= $inp) {
$inp = $inp - $bits[$x];
$store[$x] = 1;
} else {
$store[$x] = 0;
}
}
$store_rvs = array_reverse($store);
if($a % 8 === 0) {
echo "</table></td><td><table>";
}
echo "<tr>";
for($b=0; $b<count($store_rvs); $b++) {
if($store_rvs[$b] == '1') {
echo "<td class='cell blk'></td>";
} else {
echo "<td class='cell wht'></td>";
}
}
echo "</tr>";
}
echo "</table></td></tr></table>";

XML: Show two child nodes with the same name in php

I have a problem with showing my xml into a php page. I have an xml that looks like this (obviously its only a part of it because it really to long to post it all).
It all goes well until it cames to the "genre", I have two values for it and I don't know how to show them at the same time.
<movie>
<id>4441</id>
<title>Rudderless</title>
<title_long>Rudderless (2014)</title_long>
<year>2014</year>
<rating>7.5</rating>
<runtime>105</runtime>
<genres>
<genre>Comedy</genre>
<genre>Drama</genre>
</genres>
</movie>
(an important thing to notice is that not every movie will have two genre, sometimes there is only one and sometime two or three)
This is my code right now
$genere = array();
foreach ($xml->data->movies->movie->genres as $row) {
foreach ($row->children() as $key => $val) {
if ($key == "genre") {
$genere[] = $val;
}
}
}
//and then I'll print
for ($i = 0; $i < 20 ; $i++) {
echo "<div class=text><b>" . $genere[$i] . "</b></div>";
}
When I'm doing this it will print only for the first item of the array, and the others just give me a "Notice: Undefined offset: 1 in /path/ on line 53"
I've tried to follow some guides but it was a failure
What am I doing wrong?
/--Edit--/
<?php
$xml = simplexml_load_file("https://yts.to/api/v2/list_movies.xml")
$titolo = array();
$locandina = array();
$anno = array();
$durata = array();
$genere = array();
foreach ($xml->data->movies->movie as $element)
{
foreach($element->children() as $key => $val)
{
$chiave = $key;
$valore = $val;
if ($key == "title")
{
$titolo[] = $val ;
}
if ($key == "medium_cover_image")
{
$locandina[] = $val ;
}
if ($key == "year")
{
$anno[] = $val ;
}
if ($key == "runtime")
{
$durata[] = $val;
}
}
}
foreach ($xml->data->movies->movie->genres as $row)
{
foreach($row->children() as $key => $val)
{
if ($key == "genre")
{
$genere[] = $val;
}
}
}
var_dump($genere);
for ($i=0 ; $i<20 ; $i++)
{
echo "<div class=totbox>";
echo "<div class=box><img src=" . $locandina[$i] . "></div>";
echo "<div class=text><b>" . $titolo[$i] . "</b> - " . $anno[$i] . "</div>";
echo "<div class=text><b>" . $genere[$i] . "</b></div>";
echo "<div class=text><b> Durata:" . $durata[$i] . "</b></div>";
echo "</div>";
}
?>
UPDATED - Code fixed. Please, try now.
<?php
$xml = simplexml_load_file("https://yts.to/api/v2/list_movies.xml")
$titolo = array();
$locandina = array();
$anno = array();
$durata = array();
$genere = array();
$i = 0;
foreach ($xml->data->movies->movie as $element) {
foreach ($element->children() as $key => $val) {
$chiave = $key;
$valore = $val;
if ($key == "title") {
$titolo[] = $val;
}
if ($key == "medium_cover_image") {
$locandina[] = $val;
}
if ($key == "year") {
$anno[] = $val;
}
if ($key == "runtime") {
$durata[] = $val;
}
if ($key == "genres") {
for($g = 0; $g < count($xml->data->movies->movie[$i]->genres->genre); $g++) {
$genere[$i][] = $xml->data->movies->movie[$i]->genres->genre[$g];
}
}
}
$i++;
}
for ($i = 0; $i < count($titolo); $i++) {
echo "<div class=totbox>";
if (isset($locandina[$i])) {
echo "<div class=box><img src=" . $locandina[$i] . "></div>";
}
echo "<div class=text><b>" . $titolo[$i] . "</b> - " . $anno[$i] . "</div>";
foreach ($genere[$i] as $genResult) {
echo "<div class=text><b>" . $genResult . "</b></div>";
}
echo "<div class=text><b> Durata:" . $durata[$i] . "</b></div>";
echo "</div>";
}
I hope this helps!
Look on my code, based on yours. PHP file:
<?php
$xml = new SimpleXMLElement(file_get_contents('test.xml'));
$genere = array();
foreach ($xml->genres as $row) {
foreach ($row->children() as $key => $val) {
if ($key == "genre") {
$genere[] = $val;
}
}
}
//and then I'll print
foreach ($genere as $genre) {
echo "<div class=text><b>" . $genre . "</b></div>";
}
XML file:
<movie>
<id>4441</id>
<title>Rudderless</title>
<title_long>Rudderless (2014)</title_long>
<year>2014</year>
<rating>7.5</rating>
<runtime>105</runtime>
<genres>
<genre>Comedy</genre>
<genre>Drama</genre>
</genres>
</movie>
Its work fine, test it.
Based on your full xml file, look on this:
<genres>
<genre>Horror</genre>
</genres>
You have only one genre on first position, so its work fine. You need to loop on movie tag first, not genres. So put your genre tag inside movie foreach.
Like:
foreach($element->children() as $key => $val)
{
if ($key == "genres")
{
// your loop, based on $val variable!
}

Build one object from foreach loop

I want to take an array I build from a result set, encode it and then put it into a single object. My problem is I am making a lot of objects, but I want all my data to be in one object. The problem is that I echo out multiple objects from my json encode on my foreach loop. How would I take all that data I get out of that foreach loop and put it into one object? Any help is appreciated. Below is my code. Basically, what I need is this.
{"item1":"itemdata","category":"mycategory"}
but all in one object. I don't want multiple {} {} {}
$counter = 0;
$itemID = '';
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build['bid'] = $bid;
$build['id'] = $ID;
$build['item_desc'] = $description;
}
$itemID = $result['item_id'];
$counter++;
echo json_encode($build);
}
Create an array to hold the smaller arrays before your loop.
$fullData = array();
Then, inside your loop after you finish your build array add the build array to the fullData array.
$fullData[] = $build;
remove your current json_encode() and then, outside the loop.
echo json_encode($fullData);
This is what it would be changed to:
<?php
$counter = 0;
$itemID = '';
$fullData = array();
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build['bid'] = $bid;
$build['id'] = $ID;
$build['item_desc'] = $description;
}
$itemID = $result['item_id'];
$counter++;
$fullData[] = $build;
}
echo json_encode($fullData);
?>
Change this
$counter = 0;
$itemID = '';
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build['bid'] = $bid;
$build['id'] = $ID;
$build['item_desc'] = $description;
}
$itemID = $result['item_id'];
$counter++;
echo json_encode($build);
}
To
$counter = 0;
$itemID = '';
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build[] = array('bid'=>$bid,'id'=>$ID,'item_desc'=>$description);
}
$itemID = $result['item_id'];
$counter++;
}
echo json_encode($build);

echo sql or display "no items"

The following needs to be displayed:
Display all items of a certain fabric
If no fabrics are available in the sql display "no result"
The code is fully functional for the first point but does not support the second feature.
Many thanks for helping out.
//echo $sql;
$data = "";
$ii = 0;
$m = 0;
while($myrow = mysql_fetch_array($result)){
$ii++;
$m++;
if ($m == 1) $data = $data."<div class=\"page current\" id=\"gallery\">";
elseif ($ii == 1) $data = $data."<div class=\"page\" id=\"gallery\">";
$data = $data."<img src=\"".$image_directory.$myrow['thumbnail']."\" width=\"100 px\" height=\"100 px\"><div class=\"fb_name\">".$myrow['name']."</div>\n";
if ($ii == 10) {
$data = $data."</div>";
$ii = 0;
}
}
if ($ii != 10) {
$data = $data."</div>";
}
if (empty($data)) echo "No result";
else echo $data;
if($result && mysql_num_rows($result)>0)
{
$data = "";
$ii = 0;
$m = 0;
while($myrow = mysql_fetch_array($result)){
$ii++;
$m++;
if ($m == 1) $data = $data."<div class=\"page current\" id=\"gallery\">";
elseif ($ii == 1) $data = $data."<div class=\"page\" id=\"gallery\">";
$data = $data."<img src=\"".$image_directory.$myrow['thumbnail']."\" width=\"100 px\" height=\"100 px\"><div class=\"fb_name\">".$myrow['name']."</div>\n";
if ($ii == 10) {
$data = $data."</div>";
$ii = 0;
}
}
if ($ii != 10) {
$data = $data."</div>";
}
}else
echo('No Result');
if($result)
{
while()
{
-----
--
-
}
}
else
echo "No Result";
You could use the following modified code, but it still creates a new <div [...] id="gallery"> every ten iterations. Note that HTML IDs must be unique.
if ( ( !$result ) || ( 0 == mysql_num_rows( $result ) ) ) {
echo 'No result';
}
else {
$data = "";
$ii = 0;
$m = 0;
while ( $myrow = mysql_fetch_array( $result ) ) {
$ii++;
$m++;
if ( $m == 1 ) {
$data .= '<div class="page current" id="gallery">';
}
elseif ( $ii == 1 ) {
$data .= '<div class="page" id="gallery">';
}
$data .= '<img src="' . $image_directory . $myrow['thumbnail'] . '" width="100px" height="100px"><div class="fb_name">' . $myrow['name'] . "</div>\n";
if ( $ii == 10 ) {
$data .= "</div>";
$ii = 0;
}
}
if ( $ii != 10 ) {
$data .= "</div>";
}
echo $data;
}

Categories