I have an array $result and I want to echo $image for the first item only. My code this is:
<?php
foreach ($result as $item)
{
$image = $item->image;
$id = $item->id;
$cat = $item->catid;
}
?>
i want echo $image in first item and don't echo it Second, or third, etc item
$item = reset($array);
// do stuff with $item here
^ gets the first item of the array without removing it.
Or just break before the closing } in your code.
<?php
$first = true;
foreach ($result as $item)
{
$image = ($first) ? $item->image : '';
$id = $item->id;
$cat = $item->catid;
$first = false;
}
?>
if you want display only first item, you can use array_shift
$item = array_shift($result);
$image = $item->image;
$id = $item->id;
$cat = $item->catid;
You can count your iteration and print only at first run
$i=o;
foreach ($result as $item)
{
$image = $item->image;
$id = $item->id;
$cat = $item->catid;
if($i==0)
{
echo $image;
}
$i++;
}
$arr = array('foo', 'baz', 'baz');
reset($arr);
$first = current($arr);
echo $first->image; // outputs 'foo'
Try this:
<?php
foreach ($result as $item)
{
$image = $result[0]->image;
$id = $item->id;
$cat = $item->catid;
}
?>
Related
Hello can you please help that how i can get description by this loop ?
$timepicker = $_POST['timepicker'];
$discription = $_POST['description'];
foreach( $timepicker as $key => $n )
{
print "".$n." ".$discription[$key]."\n";
}
foreach( $discription as $value)
{
print $value."\n";
}
<?php
for ($i = 0, $i<= count($_POST['timepicker']); $i++){
echo $timep=$_POST['timepicker'][$i]."<br>";
echo $name = $_POST['fullname'][$i]."<br>"; // get name
echo $job = $_POST['description'][$i]."<br>"; // get jobtitle
}
?>
The correct Answer is :-
foreach( $discription as $value)
{
print $value."\n";
}
Hey I have an array that contains an array:
$outPutResults = array();
while($row = mysqli_fetch_array($results))
{
$outPutResults[] = $row['industry'];
$outPutResults[] = $row['location'];
$outPutResults[] = $row['title'];
$outPutResults[] = $row['description'];
}
$searchResults[] = $outPutResults;
I am little confused how I would echo the contents.
As far as I am aware $outputresults[] should now be contained within $searchresults[].
To output the content I'm using :
foreach ($searchResults[0] as $item) {echo $item;}
But this is only echoing the first set of results so rather than having to repeat the above and changing the number (0) each time how would i do it so it outputs all the sub arrays?
Just nest your foreach:
foreach ($searchResults as $row) {
foreach($row as $item) {
echo $item;
}
}
$outPutResults = array();
$i = 0;
while($row = mysqli_fetch_array($results))
{
$outPutResults[$i] = $row;
$i++;
}
foreach ($outPutResults as $items)
foreach($items as $item)
echo $item;
Why are you doing
$searchResults[] = $outPutResults;
instead of just
$searchResults = $outPutResults;
Then you don't have to worry about nesting your foreach statements.
You should nest two loops. For example like this:
foreach ($searchResults as $array) {
foreach ($array as $item){
echo $item;
}
}
I am trying to get category names in category path based on product id in magento.
Suppose My Product Id = 1 and In that I define category5 (id = 5) and I get category path like 2/3/5. Instead of this type of category path I need category path like category2/category3/category5. That means I need category names in path Instead of category Ids. I got this by using following code but its takes so much time. I need to reduce processing time.
Please give me suggestions for how can I reduce process time.
$category_model = Mage::getModel('catalog/category');
$product_model = Mage::getModel('catalog/product');
$all_cats = array();
$product_model->reset();
$_product = $product_model->load($entityId);
$all_cats = $product_model->getCategoryIds($_product);
$main_cnt = count($all_cats);
$cat_str_main = '';
$j = 0;
foreach($all_cats as $ac)
{
$root_category = $category_model->load($ac);
$cat_path = $root_category->getPath();
$cat_arr = explode("/",$cat_path);
$cnt = count($cat_arr);
$cat_str = '';
$main_str = '';
$i=0;
foreach($cat_arr as $ids)
{
$root_category = $category_model->load($ids); //load root catalog
if($i == 2)
{
$cat_str = $category_model->getName();
}
else if($i > 2)
{
$cat_str = $cat_str."/".$category_model->getName();
}
$i = $i+1;
}
if($j < 1)
{
$cat_str_main = $cat_str;
}
else
{
$cat_str_main = $cat_str_main .",".$cat_str;
}
$j = $j+1;
}
Thanks.....
You should use the category collection instead of load for each category to reduce the database queries.
Edit:
I have written you a code sample. I assume you have the category ID of the category of which you want to get the names of the path as $categoryId:
$category = Mage::getModel('catalog/category')->load($categoryId);
$collection = $category->getResourceCollection();
$pathIds = $category->getPathIds();
$collection->addAttributeToSelect('name');
$collection->addAttributeToFilter('entity_id', array('in' => $pathIds));
$result = '';
foreach ($collection as $cat) {
$result .= $cat->getName().'/';
}
I think you should look into magento catalog url rewrites which handles this issue for you... in your magento admin it should be in catalog >> URL rewrite management
Edit:
Because you want to do it in some other page you can simply do:
$store = Mage::app()->getStore();
$product_url = $store->getBaseUrl().$product->getUrlPath();
$category_url = $store->getBaseUrl().$category->getUrlPath();
Here is solution which works quicker than #mpaepper suggestion. My loads the collection only once and doesn's ask database then.
echo "################################", PHP_EOL;
$collection = Mage::getResourceModel('catalog/category_collection');
/* #var $collection Mage_Catalog_Model_Resource_Category_Collection */
$pattern = '1/2/';
$collection->addNameToResult()
->addPathFilter($pattern . '.+');
$categories = array();
foreach ($collection as $id => $_cat) {
/* #var $_cat Mage_Catalog_Model_Category */
$path = explode('/', $_cat->getPath());
$namedPath = [];
foreach ($path as $_id) {
$subcat = $collection->getItemById($_id);
if ($subcat) {
$namedPath[] = $subcat->getName();
}
}
$categories[implode('/', $namedPath)] = $id;
}
print_r($categories);
echo $collection->count(), $collection->getSelect()->assemble(), PHP_EOL;
Here is code Magento : get Category Name with category path. please try it . I hope it will help you.
<?php
set_time_limit(0);
require_once '../app/Mage.php';
Mage::app();
?>
<table class="category-data" border="1" align="center">
<tr>
<td><h2>Category Path</h2></td>
<td><h2>Category Id</h2></td>
</tr>
<?php
$category = Mage::getModel('catalog/category');
$tree = $category->getTreeModel();
$tree->load();
$ids = $tree->getCollection()->getAllIds();
$categories = array();
if ($ids)
{
foreach ($ids as $id)
{
$category->load($id);
$root = 'Root Catalog';
$isRoot = strtolower($root);
$categoryName = strtolower($category->getName());
if($categoryName == $isRoot){
continue;
}
$categories[$id]['name'] = $category->getName();
$categories[$id]['path'] = $category->getPath();
}
foreach ($ids as $id)
{
$path = explode('/', $categories[$id]['path']);
$len = count($path);
$string = '';
if($id > 2){
foreach ($path as $k=>$pathId)
{
$separator = '';
if($pathId > 2){
if($k != $len-1){ $separator = ' || ';}
$string.= $categories[$pathId]['name'] . $separator;
}
$cnt++;
}
?>
<tr>
<td><?php echo $string; ?></td>
<td><?php echo $id; ?></td>
</tr>
<?php
}
?>
<?php
}
}
?>
</table>
Currently I have this code:
<?php
echo '<meta name="robots" content="noindex">';
$arr = json_decode(file_get_contents("http://media1.clubpenguin.com/play/en/web_service/game_configs/ paper_items.json"),true);
foreach($arr as $item) {
$label = $item['label'];
$cost = $item['cost'];
$id = $item['paper_item_id'];
$member = $item['is_member'];
if ($member == "1") {
$member = "Yes";
}else{
$member = "No";
}
echo "$label = $id = $member = $cost";
echo ",<br>";
}
?>
What this code does it that it adds a tag after every line. This is the snippet that it happens in:
echo "$label = $id = $member = $cost";
echo ",<br>";
What I want is at the last line for the line echo ",<br>"; to NOT be ran. How do I do this? Please help!
Try this:
$result = array();
foreach($arr as $item) {
...
$result[] = "$label = $id = $member = $cost";
}
echo implode('<br />', $result);
Idea is to store all rows in array and join items with BR tag after your loop finished working.
Try this one:
<?php
$str = '';
$str .= '<meta name="robots" content="noindex">';
$arr = json_decode(file_get_contents("http://media1.clubpenguin.com/play/en/web_service/game_configs/ paper_items.json"),true);
foreach($arr as $item) {
$label = $item['label'];
$cost = $item['cost'];
$id = $item['paper_item_id'];
$member = $item['is_member'];
if ($member == "1") {
$member = "Yes";
}else{
$member = "No";
}
$str .= "$label = $id = $member = $cost";
$str .= ",<br>";
}
echo substr($str, 0, -5);
?>
I like ioseb's explode solution, but here's another easy way:
foreach($arr as $item) {
$first = isset($first) && print ",<br>";
// ...
echo "$label = $id = $member = $cost";
}
This prints the line break on all but the first iteration - but before the text, just make sure $first isn't set before running it.
I would recommend storing all your items in a string rather than echoing as you go. then you can remove whatever trailing characters you want when you're done before you echo just once at the end with a simple regex like...
echo preg_replace('/\<br\/\>$/','', $myTotalOutputString);
A small rewrite of your code:
<?php
echo '<meta name="robots" content="noindex">';
$arr = json_decode(file_get_contents("http://media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.json"), true);
$outArray = array();
foreach($arr as $item) {
$label = $item['label'];
$cost = $item['cost'];
$id = $item['paper_item_id'];
$member = ($item['is_member'] == '1') ? "Yes" : "No";
$outArray[] = "{$label} = {$id} = {$member} = {$cost}";
}
echo implode(',<br>', $outArray);
?>
Quick one-liner using rtrim:
echo rtrim('test <br />', '<br />');
But I voted for the implode answer above.
I am trying to extract some info from a website using simple_html_dom.
Currently I am using:
foreach ($html->find('div.product') as $results) {
foreach ($results->find('div.image') as $img) {
echo $img;
}
foreach ($results->find('a.title') as $title) {
echo $title->plaintext;
}
foreach ($results->find('div.price') as $price) {
echo $price;
}
}
Which works fine. However I need to be able to echo each variable outside of the foreach loop. If I do that using the above code, only the final result will be displayed, i.e. out of the 10 products I am trying to extract only the 10th will be displayed.
Is there a way I can use an array to store all the results from each foreach loop then echo them out once the overall loop is finished?
Something like this:
foreach ($html->find('div.product') as $results) {
foreach ($results->find('div.image') as $img) {
array($img);
}
foreach ($results->find('a.title') as $title) {
array($title->plaintext);
}
foreach ($results->find('div.price') as $price) {
array($price);
}
}
echo array($img);
echo array($title);
echo array($price);
Sorry if this question is confusing I don't have the best grasp on PHP, especially arrays!
$array_img = array();
$array_title = array();
$array_price = array();
foreach ($html->find('div.product') as $results) {
foreach ($results->find('div.image') as $img) {
$array_img[] = $img;
}
foreach ($results->find('a.title') as $title) {
$array_title[]= $title->plaintext;
}
foreach ($results->find('div.price') as $price) {
$array_price[]= $price;
}
}
echo '<pre>';
print_r($array_img);
print_r($array_title);
print_r($array_price);
echo '</pre>';
$images = array();
foreach ($html->find('div.product') as $results) {
foreach ($results->find('div.image') as $img) {
$images[] = $img; // append $img to the $images array
}
}
var_dump($images);
Do the same for the title and price data as well.
$img = array();
$title = array();
$price = array();
foreach ($html->find('div.product') as $results) {
$img[] = $results->find('div.image');
$title[] = $results->find('a.title');
$price[] = $results->find('div.price');
}
print_r($img);
print_r($title);
print_r($price);
Not sure if I completely understand you question, try the following.
$priceList = $titleList = $imgList = array();
foreach ($html->find('div.product') as $results) {<br/>
foreach ($results->find('div.image') as $img) {<br/>
$imgList[] = $img;<br/>
}<br/>
foreach ($results->find('a.title') as $title) {<br/>
titleList[] = $title;<br/>
}<br/>
foreach ($results->find('div.price') as $price) {<br/>
priceList[] = $price;<br/>
}<br/>
}<br/>
foreach ($imgList as $img) {<br/>
echo $img;<br/>
}<br/>
And so on...