Hi i have a script in which there is a foreach within a foreach. The first foreach is used for id which is unique, but the second foreach used is for related images of a product which should loop according to the number of images. However, it restricts me to fetch only one related image, how can i get all related images?
$i=0;
foreach ($collection as $product_all) {
//echo $product_all->getId().'<br/>';
if($i==10) break;
$id = $product_all->getId();
$neew = Mage::getModel('catalog/product')->load($id);
//echo'<pre>';
echo 'active products id ===='.$neew ->getId().'<br/>';
echo 'active products name ===='.$neew->getname().'<br/>';
echo 'active products style_ideas ===='.$neew->getstyle_ideas().'<br/>';
echo 'active products size and fit ===='.$neew->getsize_fit().'<br/>';
echo 'active products short description ===='.$neew->getshort_description().'<br/>';
echo 'active products description ===='.$neew->getdescription().'<br/>';
//print_r($neew);
if (count($neew->getMediaGalleryImages()) > 0){
$i = 0 ;
$j = 0 ;
foreach ($neew->getMediaGalleryImages() as $_image){
$relative_image = Mage::helper('catalog/image')->init($neew->getProduct(), 'image', $_image->getFile())->resize(2000);
$relative_image1 = str_replace('/webApps/migration/productapi/new/','/',$relative_image);
//echo 'relative_image => '.$relative_image1.'<br/>';
$relative_image_save = $relative_image1 ;
$relative_image_save1 = explode('/', $relative_image_save);//explode / to get only image name
$end1 = end($relative_image_save1);
$relative_image3 = $end1;
//$handle1 = fopen( $relative_image3, 'w') or die('Cannot open file: '. $relative_image);
$path12 = '/mnt/aviesta/development/webApps/migration/productapi/new/'.'sku-'.$neew->getsku().'_' .$i++.'.jpg';
copy($relative_image_save, $path12);
echo 'relative image with sku path_'.$j++.' ====>'.$path12.'<br/><br/>';
}
}
$i++;
}
From your code i think the problem can be solved by initializing an array before your 2nd foreach loop , and storing the images in that array can help you out in fetching all the images....This is what i understood from your question. If this is correct.., than the below code may work....
foreach()
{
//Your code....
$image_list = array();
$i = 0;
foreach()
{
// Your usual code
$image_list[$i] = your_image;
//storing images one-by-one in your variable..
$i++;
}
}
You can later return the variable or just print_r(); to get the output
i think i have post the question in little hurry, the script works fine , for the initial products there was a single images for the products but for the newer products there are multiple images and the script works fine , thanks to all of you to respond the post .....
Related
Still new to php programming and I have been trying to scrape data from a table in a website (https://en.wikipedia.org/wiki/HP_EliteBook). Particularly getting elitebook laptops that use intel graphics card but I am having issues going about the code to access the data in the element I want. If anyone could help me to an idea I would be grateful.
Been using the simplehtmldom.php and the foreach loop to try and access the td element of the table and print the result but all I get are a variety of errors. Attached is the code I am currently trying
<?php
include('simple_html_dom.php');
$html = file_get_html('https://en.wikipedia.org/wiki/HP_EliteBook');
$table= $html->find('table[class="wikitable"]',1);
//$tdata= array();
foreach($table->find('tr') as $tr){
$tdata[0] = $tr->find('td',0); //find the first td starts from 0
$tdata[1] = $tr->find('td',1);
$tdata[2] = $tr->find('td',2);
$tdata[3] = $tr->find('td',3);
$tdata[4] = $tr->find('td',4);
$tdata[5] = $tr->find('td',5);
$data[]= $tdata;
}
print_r($data);
?>
I at least expected to see the data from all the other cells
Table column length is different, for this table use index 3 and 4 for getting Graphic Card name.
<?php
include_once('/simple_html_dom.php');
$html = file_get_html('https://en.wikipedia.org/wiki/HP_EliteBook');
$table = $html->find('table.wikitable', 2);
$useIntel = array();
foreach ($table->find('tr') as $tr) {
if (!$tr->find('td', 0))
continue;
for ($i = 3; $i <= 4; $i++)
if ($tr->find('td', $i) && strpos($tr->find('td', $i)->innertext, 'Intel') !== false) {
$useIntel[] = $tr->find('td', 0)->innertext;
continue 2;
}
}
echo "<pre>";
var_dump($useIntel);
I want to set a limit for the output but I don't know how and where. Can anyone help me?
The code (excerpt):
// Editable values
// Show how many items, defaults to 10?
$max = 8;
// Fetch the items
if (!isset($actions) || empty($actions))
$actions = fillActionArray($datestart, $dateend, $section_id);
//Generating the news items
if (is_array($actions)){
foreach($actions as $item){
// Build url like : pages/kalendar.php?year=1900&month=01&day=03&id=2&detail=1
$ds = $item['date_start'];
$link = $page_link.'?year='.(substr($ds,0,4)).'&month='.(substr($ds,5,2)).'&day='.(substr($ds,8,2)).'&id='.$item['id'].'&detail=1';
}
}
Use array chunk on that news items variable "actions" based on the $max value http://php.net/manual/en/function.array-chunk.php
check the output of this -> print_r(array_chunk($actions, $max));
This is for me the simplest way:
//Generating the news items
$i=0;
if (is_array($actions)){
foreach($actions as $item)
if ($i < $max) {
// Build url like : pages/kalendar.php?year=1900&month=01&day=03&id=2&detail=1
$ds = $item['date_start'];
$link = $page_link.'?year='.(substr($ds,0,4)).'&month='.(substr($ds,5,2)).'&day='.(substr($ds,8,2)).'&id='.$item['id'].'&detail=1';
$i +=1;
?>
I currently have the following code, it works great, but I've never tried to do anything more complex with this sort of thing. I'm wondering how I can add more variables to my result output.
$check_alt_sizes = mysqli_query($link, "SELECT model, version, size, category FROM items WHERE model = '$model' AND size != '$category' AND id != '$item_id'");
if (mysqli_num_rows($check_alt_sizes) >= 1) {
$group = array();
while ($row = mysqli_fetch_assoc($check_alt_sizes)) {
$group[ $row['category'] ][] = $row;
}
then later
foreach ($group as $sizes => $alt_size_urls) {
foreach ($alt_size_urls as $alt__size_url) {
echo "<a href='/items/"; echo "$alt_size_url[slug]"; // slug set elsewhere
echo "'>";
echo "$sizes</a>";
}
}
}
Now the $sizes part displays a list of sizes that I have gotten from grabbing $row['category'] in the initial $group from the query. What I would like to know is, how can I add more variables to this group, I've only ever dealt with doing it this way, never expanding it.
Currently it displays
Alternate Sizes:
size1
size2
but I would like to be able to add version as well, such as
Alternate Sizes:
Version1 - size1
Version2 - size1
Version3 - size2
I tried doing this:
echo $row['version']; echo "$sizes</a></p></li>";
But that just uses the first version found and applies it to every item. obviously because $sizes is looping and the version echo is not. How do I go about doing this?
I modified your source code with this one:
$group_size = "";
foreach ($group as $sizes => $alt_size_urls) {
$group_size .= "Alternate Sizes: <br>";
$ctr = 0;
foreach ($alt_size_urls as $alt__size_url) {
$group_size .= "<a href='/items/' " . $alt_size_url[slug] . (++$ctr) . "'>" . $sizes . "</a><br>";
}
}
echo $group_size;
I am trying to insert records into mysql database tables using Simple HTML DOM.
Checkout the codes..
<?php
$startpage=1;
$endpage=2;
for($p=$startpage;$p<=$endpage;$p++)
{
$html = file_get_html("http://examplesite.com/index.php?page=$p");
// connect to main page links
foreach($html->find('div.tt-name a[1]') as $link)
{
$linkHref = $link->href;
$url[] = $conn->real_escape_string(trim($linkHref));
//loop through each link
$linkHtml = file_get_html('http://examplesite.com'.$linkHref);
$title=array();
$size=array();
foreach($linkHtml->find('div#content h1') as $title2)
{
$title[] = $conn->real_escape_string(trim($tit2));
}
foreach($linkHtml->find('div.torrentinfo table tr[3]') as $size2)
{
$size[] = $conn->real_escape_string(trim($size2));
}
$qv = $conn->query("INSERT INTO data (title, size, url) VALUES('$title[$i]', '$size[$i]', '$url[$i]')");
if($qv){print "<br>Record Inserted..!!";}
else {print "<br>".$conn->error;}
$i++;
}
}
?>
Everything is working fine only problem with $url[] on line 11 its not inserting all records, its only inserting first record.
I guess its not inside the loop, how to fix this?
Just put $i=0 out of the for loop and fix incrementing of x to $i++
I have fixed it, this line
$url[] = $conn->real_escape_string(trim($linkHref));
needed to move down near to sql query only.
On a product page I want to show 4 other products selected randomly, but never the product that is already being displayed. The product id of the displayed one is $_product->getId() and all the products go into a $result[] array like this:
foreach($collection as $product){
$result[]=$product->getId();
}
I'm using $need = array_rand($result, 4); to get the ids of the 4 random products, but it might include the id of the product on display. How do I exclude $_product->getId() from the $need[] array? Thank you.
Don't put id of the product you don't want to show into $result:
$currentProductId = $_product->getId();
foreach ($collection as $product) {
if ($product->getId() != $currentProductId) $result[] = $product->getId();
}
Is it acceptable to just not put the current product ID in the array?
foreach($collection as $product) {
if( $product != $_product) $result[] = $product->getId();
}
You might generate your random numbers first, like so:
$rands = array();
while ($monkey == false){
$banana = rand(0,4);
if (in_array($banana, $rands) && $banana != $_product->getId()){ $rands[] = $banana; }
if (sizeOf($rands) == 4){
$monkey = true;
}
}
Then you could pipe them through your product grabber. Obviously, you'd need to figure out the bounds for rand yourself but you know more about your app than I do. Picking your numbers first is much cheaper computationally than pulling records and THEN checking to make sure that they're unique.
Of course, if this is database-backed, you could solve it much more elegantly by writing a new query.
If you use the product id as the index $result[] in result, you can remove the current product from the $result array with unset() before making the call to array_rand() like so:
foreach($collection as $product){
$result[$product->getId()] = $product->getId();
}
unset($result[$_product->getId()]);
$need = array_rand($result, 4);
This approach saves you from having to use the values in $need to look up the product id in your $result[] array, since the values in $need will be your product ids.