Foreach last item with condition - php

foreach ($orderItems as $item) {
if ($item->isNotCancelled()) {
echo 'ITEM....<br />';
// if last NOT CANCELLED item:
echo '<strong>ITEM....</strong><br />';
} else {
// ignored completely
}
}
I need to add <strong> arround the last item which did not get cancelled... I know how to check the last item of an array or iterator, but with the condition in the if case, how'd you do this?
Will I need 2 loops?
Update & Solution: I solved this by reversing the logic and to find the first item rather than the last.
I'll keep the question up if someone wants to comment or answer anyways.

try this:
$i=0;
$counter=0;
foreach ($orderItems as $item) {
if ($item->isNotCancelled()) {
$counter=$i;
}
$i++;
}
$i=0;
foreach ($orderItems as $item) {
if ($item->isNotCancelled()) {
if( $counter==$i){
echo "<strong>".$item."</strong></br>"
}
}
$i++;
}
what about this?

$lastNonCancelledItem = null;
foreach ($orderItems as $item) {
if ($item->isNotCancelled()) {
echo 'ITEM....<br />';
$lastNonCancelledItem = $item;
} else {
// ignored completely
}
}
echo '<strong>' $lastNonCancelledItem; //profit
If display these items is a complex task that you do not wish to repeat in 2 places make some sort of function to display the item
$lastNonCancelledItem = null;
foreach ($orderItems as $item) {
if ($item->isNotCancelled()) {
$view->showItem($item);
$lastNonCancelledItem = $item;
} else {
// ignored completely
}
}
echo $view->showItem($lastNonCancelledItem, TYPE_STRONG); //profit (or whatever)

Can you try this,
$coun = count($orderItems);
$i=1;
foreach ($orderItems as $item) {
if ($item->isNotCancelled()) {
echo 'ITEM....<br />';
// if last NOT CANCELLED item:
}else {
// ignored completely
}
if($i==($coun-1))
echo '<strong>ITEM....</strong><br />';
$i++;
}

Related

Simplify multiple nested if()'s

Can someone help me simplify this complex nested if()'s algorithm? I know it can be simplified, but I'm afraid I'll mess up with the multiple conditions if I trust myself.
$groups = array();
foreach ($items as $item) {
if ($item['group_code']) {
if (array_key_exists($item['group_code'], $groups)) {
if (mb_strlen($groups[$item['group_code']]) < mb_strlen($item['title'])) {
$groups[$item['group_code']] = $item['title'];
}
} else {
$groups[$item['group_code']] = $item['title'];
}
} else {
$groups[$item['item_code']] = $item['title'];
}
}
What I want is to create an index of product titles in $groups. If the group_code key exists for each item, then I want to store the lengthier title of all items belonging to that group. If group_code doesn't exist (meaning it's a single product and not a grouped one), I want to store the title of that item using the item_code instead (this is the simplest condition, and no length comparison is needed here).
What about checking the else conditions first?
foreach ($items as $item) {
if (!isset($item['group_code'])){
$groups[$item['item_code']] = $item['title'];
} else if (!array_key_exists($item['group_code'], $groups)){
$groups[$item['group_code']] = $item['title'];
} else if (mb_strlen($groups[$item['group_code']]) < mb_strlen($item['title'])){
$groups[$item['group_code']] = $item['title'];
}
}
I'd simplify it like this (php 7+):
foreach ($items as $item) {
$t = $item['title'];
$c = $item['group_code'] ?? $item['item_code'];
if (mb_strlen($t) > mb_strlen($groups[$c] ?? '')) $groups[$c] = $t;
}

Filtering an array with foreach and for loop

I'm pulling data from mssql database into an array called
$results2
I need to echo out each 'Item' only one time, so this example should only echo out:
"52PTC84C25" and "0118SGUANN-R"
I can do this easily with:
$uniqueItems = array_unique(array_map(function ($i) { return $i['ITEM']; }, $results2));
The issue is when i try to echo out the other items associated with those values. I'm not sure how to even begin on echoing this data. I've tried:
foreach($uniquePids as $items)
{
echo $items."<br />";
foreach($results2 as $row)
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
}
}
This returns close to what I need, but not exactly:
This is what I need:
Assuming your resultset is ordered by ITEM...
$item = null; // set non-matching default value
foreach ($results2 as $row) {
if($row['ITEM'] != $item) {
echo "{$row['ITEM']}<br>"; // only echo first occurrence
}
echo "{$row['STK_ROOM']}-{$row['BIN']}<br>";
$item = $row['ITEM']; // update temp variable
}
The if condition in the code will check if the ITEM has already been printed or not.
$ary = array();
foreach($results2 as $row)
{
if(!in_array($row['ITEM'], $ary))
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
$ary[] = $row['ITEM'];
}
}

How to get more than 20 results for nearby places using google api

<?php
{
$references = array();
$names = array();
$lat="26.177194999999998";
$long="91.77591333333334";
$count=0;
$placeSearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&radius=10000&types=mosque&sensor=true&key=AIzaSyASP02W3Qwb75Ruep3isiGstqA7Y2HXjGw";
$placeSearchJSON = file_get_contents($placeSearchURL);
$dataArray = json_decode($placeSearchJSON);
if(isset($dataArray->status) &&$dataArray->status == "OK") {
foreach( $dataArray->results as $details) {
array_push($references, $details->reference);
array_push($names, $details->name);
}
}
foreach ($names as $name) {
echo $name."<br>";
}
echo "next token".$dataArray->next_page_token."<br>";
if(!empty($dataArray->next_page_token)) {
echo "in the if statement"."<br>";
$placeSearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&radius=10000&types=mosque&sensor=true&key=AIzaSyASP02W3Qwb75Ruep3isiGstqA7Y2HXjGw&nextpage=".$dataArray->next_page_token;
$placeSearchJSON = file_get_contents($placeSearchURL);
//echo "hello";
$dataArray = json_decode($placeSearchJSON);
if(isset($dataArray->status) &&$dataArray->status == "OK") {
foreach( $dataArray->results as $details) {
array_push($references, $details->reference);
array_push($names, $details->name);
}
}
echo "hello<br>";
}
foreach ($names as $name) {
echo $name."<br>";
}
echo "next token".$dataArray->next_page_token."<br>";
if(!empty($dataArray->next_page_token)) {
echo "in the if statement"."<br>";
$placeSearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&radius=10000&types=mosque&sensor=true&key=AIzaSyASP02W3Qwb75Ruep3isiGstqA7Y2HXjGw&nextpage=".$dataArray->next_page_token;
$placeSearchJSON = file_get_contents($placeSearchURL);
//echo "hello";
$dataArray = json_decode($placeSearchJSON);
if(isset($dataArray->status) &&$dataArray->status == "OK") {
foreach( $dataArray->results as $details) {
array_push($references, $details->reference);
array_push($names, $details->name);
}
}
echo "hello<br>";
}
foreach ($names as $name) {
echo $name."<br>";
}
?>
I get the same 20 results every time, and I have used pagination as you can see in my code. Every time I print the next page token I get a different one.
I would really appreciate if someone could point out the error in my code because I am stuck with this for quite some time. You are also most welcome to give any kind of relevant suggestion.
use pagetoken instead of nextpage in your url string and in the last two calls give only api key and page token as parameter and after each api call use sleep(2) i tried your code and it works perfectly when the following changes are made.happy coding!
<?php
//echo"hello";
$references = array();
$names = array();
$lat="26.177194999999998";
$long="91.77591333333334";
$count=0;
$placeSearchURL ="https://maps.googleapis.com/maps/api/place/radarsearch/json?location=26.177194999999998,91.77591333333334&radius=3000&types=mosque&key=your APIkey";
$placeSearchJSON = file_get_contents($placeSearchURL);
$dataArray = json_decode($placeSearchJSON);
foreach( $dataArray->results as $details) {
//echo $details->place_id;
array_push($references, $details->place_id);
}
foreach($references as $reference)
{
$count=$count+1;
//echo $count." ";
$placeSearchURL="https://maps.googleapis.com/maps/api/place/details/json?placeid=".$reference."&key=your apikey";
$placeSearchJSON = file_get_contents($placeSearchURL);
$dataArray = json_decode($placeSearchJSON);
echo $dataArray->result->name."<br>";
echo "lat ".$dataArray->result->geometry->location->lat."<br>";
echo "lon ".$dataArray->result->geometry->location->lng."<br>";
echo "address ".$dataArray->result->formatted_address."<br>";
echo "<br>";
}
?>
basically i wanted to find a way to get more than 20 places of type masjid so i first used radar search to get placeids and then for each placed_id got the information and best part is you can get arount 200 results of nearby places

Array get 2nd item

foreach($xml->xpath( 'programme[#channel="1"]' ) as $item) {
if (something) {
echo "cat.: ".$item->{'category'}. "<br>";}
If i have 2x "category" to choose, how to set it to get the second one, not the 1st in the row?
The simplest way would be to use a counter variable:
$i = 0;
foreach($xml->xpath( 'programme[#channel="1"]' ) as $item) {
if ( $i++ != 1)
echo "cat.: ".$item->{'category'}. "<br>";
However, this will include every category after the first. If you only want the second category, you could use the same approach:
$i = 0;
foreach($xml->xpath( 'programme[#channel="1"]' ) as $item) {
if ( $i++ == 2)
echo "cat.: ".$item->{'category'}. "<br>";
This gives you the second category and also ensures that you'll get the first category when there's no second one:
foreach ($xml->xpath('programme[#channel="1"]') as $item) {
if (something) {
if (isset($item->category[1]) && !empty($item->category[1])) {
echo 'cat.: '.$item->category[1].'<br />';
} else {
echo 'cat.: '.$item->category[0].'<br />';
}
}
}

php foreach loop with continue if value has already been echoed

I have a foreach loop and I need to add a continue if the value has already been echoed. I can't find the right syntax. The loop:
foreach ($results as $result) {
echo $result->date . "<br />";
}
But I need to add in a continue so that if the value has already been echoed, and it comes up again in the loop it gets skipped. I can't quite get the if/continue statement quite right.
Thoughts, suggestions, ideas?
As mentioned by #JonathanKuhn in the comments - here is how you would run that loop:
$already_echoed = array();
foreach ($results as $result) {
if (!in_array($result->date, $already_echoed)) { //check if current date is in the already_echoed array
echo $result->date . "<br />";
}
$already_echoed[] = $result->date; //store all dates in an array to check against.
}
$echoedArray = array();
foreach ($results as $result) {
if (isset($echoedArray[$result->date])) {
continue;
}
echo $result->date . "<br />";
$echoedArray[$result->date] = true;
}
$alreadyOutput = array();
foreach ($results as $result) {
if(in_array($result->date, $alreadyOutput)){
continue;
}
$alreadyOutput[] = $result->date;
echo $result->date . "<br />";
}

Categories