Restarting a PHP Loop - php

I have this piece of code
foreach($mnthArrPtrn as $m => $mn)
{
if(!isset($catName)) {
$catVals = array();
$prevCat = $catName = $pntChrtQry[0]['CAT']['categoryname'];
$pntVals .= '{name:'.$catName.',data:[';
}else if($prevCat != $catName) {
$prevCat = $catName;
$catVals = array();
$pntVals .= '{name:'.$catName.',data:[';
}
foreach($pntChrtQry as $key => $val){
$catName = $val['CAT']['categoryname'];
if($prevCat != $catName){
continue 2;
}
echo '<br />$m::'.$m;
echo '<br />$mn::'.$mn;
echo '<br />$val::'.$val[0]['MNTH'];
if($m == $val[0]['MNTH'] || $mn == $val[0]['MNTH']){
$catVals[] = $val[0]['total'];
}
}
pr($catVals);
if(!isset($catName)){
$pntVals .= ']},';
}
$catName = $val['CAT']['categoryname'];
}
1st loop iterates over a months array which are joined as a key value pair.
What I am doing here is on getting a new catName I continue the internal loop but at the same time I want to restart loop 1 with $prevCat,$catName still preserving their values.
Is this possible? Sorry If this is a silly question.
I tried converting the first one to a while statement and use a reset then but It didn't help me.

Something like this will allow you to arbitrarily restart a loop:
while (list($key, $value) = each($mnthArrPtrn)) {
if ($needToRestart) {
reset($mnthArrPtrn);
}
}
See more here.

Related

Array Showing Values from previous iteration

I have this code using an api , the first iteration is showing everything right , but at the second iteration is showing the items from the first iteration + the items from the second iteration , and the same thing at the third iteration.
I dont want that , how can i fix that problem ?
$g=0;
foreach ($matches as $match) {
$inside = $api->getMatch('123');
$pp = $api->getMatchTimeline('123');
foreach ($inside->participants as $partId) {
if ($partId->championId == $match->champion) {
$participant_id[] = $partId->participantId;
$participant_idS = $partId->stats->participantId;
foreach ($pp->frames as $p) {
foreach ($p->events as $t) {
if ($t->type == "ITEM_PURCHASED" and $t->participantId == $participant_idS) {
$item_id = $t->itemId;
$d = $api->getStaticItem($item_id);
if($d->depth == 2 or $d->depth == 3){
$itemsMade[] = $d->id;
}
}
}
}
}
}
$dt = [['match_ids' => $part, "champion" => $soloq->champion, "timestamp" => $match->timestamp, "participantId" => $participant_id[$g++], "itens" => json_encode($itemsMade)]
];
echo ' <pre>';
var_dump($dt);
echo '</pre>';
}
You need to set that array to be empty at the start of your loop. Otherwise you just keep adding to it as you see in your output.
foreach ($inside->participants as $partId) {
$itemsMade = [];

Outputting odd and even number in array

Using below array, i'm trying to use foreach loop to iterate through each item. Then i need to apply if condition to check if the given number is even and odd. I also need to create two arrays one for even and one for odd and push each number in their respective category.
So i have done this so far:
These are the two arrays i created to push through the values to.
}
$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
$array_odd = [];
$array_even = [];
foreach ($numbers as $value)
{
if (value %2 == 0)
{
$array_even = $value;
echo $array_even;
}
else
{
$array_odd = $value;
echo $array_odd;
}
I'd like to know if i'm using the correct solution or are there major errors im committing?
It will surely work like charms.
$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
$array_odd = [];
$array_even = [];
foreach ($numbers as $value)
{
if ($value %2 == 0)
{
$array_even[] = $value;
}
else
{
$array_odd[] = $value;
}
}
echo "<pre>";
print_r($array_odd);
echo "<pre>";
print_r($array_even);

Invalid argument supplied for foreach() inside if else PHP [duplicate]

Why am I getting this PHP Warning?
Invalid argument supplied for foreach()
Here is my code:
// look for text file for this keyword
if (empty($site["textdirectory"])) {
$site["textdirectory"] = "text";
}
if (file_exists(ROOT_DIR.$site["textdirectory"].'/'.urlencode($q).'.txt')) {
$keywordtext =
file_get_contents(ROOT_DIR.$site["textdirectory"].'/'.urlencode($q).'.txt');
}
else {
$keywordtext = null;
}
$keywordsXML = getEbayKeywords($q);
foreach($keywordsXML->PopularSearchResult as $item) {
$topicsString = $item->AlternativeSearches;
$relatedString = $item->RelatedSearches;
if (!empty($topicsString)) {
$topics = split(";",$topicsString);
}
if (!empty($relatedString)) {
$related = split(";",$relatedString);
}
}
$node = array();
$node['keywords'] = $q;
2
$xml = ebay_rss($node);
$ebayItems = array();
$totalItems = count($xml->channel->item);
$totalPages = $totalItems / $pageSize;
$i = 0;
foreach ($xml->channel->item as $item) {
$ebayRss =
$item->children('http://www.ebay.com/marketplace/search/v1/services');
if ($i>=($pageSize*($page-1)) && $i<($pageSize*$page)) {
$newItem = array();
$newItem['title'] = $item->title;
$newItem['link'] = buyLink($item->link, $q);
$newItem['image'] = ebay_stripImage($item->description);
$newItem['currentbid'] = ebay_convertPrice($item->description);
$newItem['bidcount'] = $ebayRss->BidCount;
$newItem['endtime'] = ebay_convertTime($ebayRss->ListingEndTime);
$newItem['type'] = $ebayRss->ListingType;
if (!empty($ebayRss->BuyItNowPrice)) {
$newItem['bin'] = ebay_convertPrice($item->description);
}
array_push($ebayItems, $newItem);
}
$i++;
}
$pageNumbers = array();
for ($i=1; $i<=$totalPages; $i++) {
array_push($pageNumbers, $i);
}
3
// get user guides
$guidesXML = getEbayGuides($q);
$guides = array();
foreach ($guidesXML->guide as $guideXML) {
$guide = array();
$guide['url'] = makeguideLink($guideXML->url, $q);
$guide['title'] = $guideXML->title;
$guide['desc'] = $guideXML->desc;
array_push($guides,$guide);
}
What causes this warning?
You should check that what you are passing to foreach is an array by using the is_array function
If you are not sure it's going to be an array you can always check using the following PHP example code:
if (is_array($variable)) {
foreach ($variable as $item) {
//do something
}
}
This means that you are doing a foreach on something that is not an array.
Check out all your foreach statements, and look if the thing before the as, to make sure it is actually an array. Use var_dump to dump it.
Then fix the one where it isn't an array.
How to reproduce this error:
<?php
$skipper = "abcd";
foreach ($skipper as $item){ //the warning happens on this line.
print "ok";
}
?>
Make sure $skipper is an array.
Because, on whatever line the error is occurring at (you didn't tell us which that is), you're passing something to foreach that is not an array.
Look at what you're passing into foreach, determine what it is (with var_export), find out why it's not an array... and fix it.
Basic, basic debugging.
Try this.
if(is_array($value) || is_object($value)){
foreach($value as $item){
//somecode
}
}

PHP Warning: Invalid argument supplied for foreach()

Why am I getting this PHP Warning?
Invalid argument supplied for foreach()
Here is my code:
// look for text file for this keyword
if (empty($site["textdirectory"])) {
$site["textdirectory"] = "text";
}
if (file_exists(ROOT_DIR.$site["textdirectory"].'/'.urlencode($q).'.txt')) {
$keywordtext =
file_get_contents(ROOT_DIR.$site["textdirectory"].'/'.urlencode($q).'.txt');
}
else {
$keywordtext = null;
}
$keywordsXML = getEbayKeywords($q);
foreach($keywordsXML->PopularSearchResult as $item) {
$topicsString = $item->AlternativeSearches;
$relatedString = $item->RelatedSearches;
if (!empty($topicsString)) {
$topics = split(";",$topicsString);
}
if (!empty($relatedString)) {
$related = split(";",$relatedString);
}
}
$node = array();
$node['keywords'] = $q;
2
$xml = ebay_rss($node);
$ebayItems = array();
$totalItems = count($xml->channel->item);
$totalPages = $totalItems / $pageSize;
$i = 0;
foreach ($xml->channel->item as $item) {
$ebayRss =
$item->children('http://www.ebay.com/marketplace/search/v1/services');
if ($i>=($pageSize*($page-1)) && $i<($pageSize*$page)) {
$newItem = array();
$newItem['title'] = $item->title;
$newItem['link'] = buyLink($item->link, $q);
$newItem['image'] = ebay_stripImage($item->description);
$newItem['currentbid'] = ebay_convertPrice($item->description);
$newItem['bidcount'] = $ebayRss->BidCount;
$newItem['endtime'] = ebay_convertTime($ebayRss->ListingEndTime);
$newItem['type'] = $ebayRss->ListingType;
if (!empty($ebayRss->BuyItNowPrice)) {
$newItem['bin'] = ebay_convertPrice($item->description);
}
array_push($ebayItems, $newItem);
}
$i++;
}
$pageNumbers = array();
for ($i=1; $i<=$totalPages; $i++) {
array_push($pageNumbers, $i);
}
3
// get user guides
$guidesXML = getEbayGuides($q);
$guides = array();
foreach ($guidesXML->guide as $guideXML) {
$guide = array();
$guide['url'] = makeguideLink($guideXML->url, $q);
$guide['title'] = $guideXML->title;
$guide['desc'] = $guideXML->desc;
array_push($guides,$guide);
}
What causes this warning?
You should check that what you are passing to foreach is an array by using the is_array function
If you are not sure it's going to be an array you can always check using the following PHP example code:
if (is_array($variable)) {
foreach ($variable as $item) {
//do something
}
}
This means that you are doing a foreach on something that is not an array.
Check out all your foreach statements, and look if the thing before the as, to make sure it is actually an array. Use var_dump to dump it.
Then fix the one where it isn't an array.
How to reproduce this error:
<?php
$skipper = "abcd";
foreach ($skipper as $item){ //the warning happens on this line.
print "ok";
}
?>
Make sure $skipper is an array.
Because, on whatever line the error is occurring at (you didn't tell us which that is), you're passing something to foreach that is not an array.
Look at what you're passing into foreach, determine what it is (with var_export), find out why it's not an array... and fix it.
Basic, basic debugging.
Try this.
if(is_array($value) || is_object($value)){
foreach($value as $item){
//somecode
}
}

Help with PHP loop

Suppose I have a multi-dimensional array of the form:
array
(
array('Set_ID' => 1, 'Item_ID' => 17, 'Item_Name' = 'Whatever'),
array('Set_ID' => 1, 'Item_ID' => 18, 'Item_Name' = 'Blah'),
array('Set_ID' => 2, 'Item_ID' => 19, 'Item_Name' = 'Yo')
)
The array has more sub-arrays, but that's the basic form-- Items in Sets.
How can I loop through this array so that I can echo the number of items in each set along with the all the items like so:
Set 1 has 2 Items: 17: Whatever and 18: Blah
Set 2 has 1 Items: 19: Yo
I'm aware that this could be done with two loops-- one to build an array, and another to loop through that array. However, I'd like to do this all with only one loop.
In your answer, you should assume that there are two display functions
display_set($id, $count) //echo's "Set $id has $count Items"
display_item($id, $name) //echo's "$id: $name"
UPDATE: Forgot to mention that the data is sorted by Set_ID because its from SQL
Right, all the examples below rely on an ordered set, the OP states it is ordered initially, but if needed a sort function could be:
// Sort set in to order
usort($displaySet,
create_function('$a,$b',
'return ($a['Set_ID'] == $b['Set_ID']
? ($a['Set_ID'] == $b['Item_ID']
? 0
: ($a['Item_ID'] < $b['Item_ID']
? -1
: 1))
: ($a['Set_ID'] < $b['Set_ID'] ? -1 : 1));'));
Straight example using a single loop:
// Initialise for the first set
$cSetID = $displaySet[0]['Set_ID'];
$cSetEntries = array();
foreach ($displaySet as $cItem) {
if ($cSetID !== $cItem['Set_ID']) {
// A new set has been seen, display old set
display_set($cSetID, count($cSetEntries));
echo ": " . implode(" and ", $cSetEntries) . "\n";
$cSetID = $cItem['Set_ID'];
$cSetEntries = array();
}
// Store item display for later
ob_start();
display_item($cItem['Item_ID'], $cItem['Item_Name');
$cSetEntries[] = ob_get_clean();
}
// Perform last set display
display_set($cSetID, count($cSetEntries));
echo ": " . implode(" and ", $cSetEntries) . "\n";
Using a recursive function it could be something like this:
// Define recursive display function
function displayItemList($itemList) {
if (!empty($itemList)) {
$cItem = array_shift($itemList);
display_item($cItem['Item_ID'], $cItem['Item_Name');
if (!empty($itemList)) {
echo " and ";
}
}
displayItemList($itemList);
}
// Initialise for the first set
$cSetID = $displaySet[0]['Set_ID'];
$cSetEntries = array();
foreach ($displaySet as $cItem) {
if ($cSetID !== $cItem['Set_ID']) {
// A new set has been seen, display old set
display_set($cSetID, count($cSetEntries));
echo ": ";
displayItemList($cSetEntries);
echo "\n";
$cSetID = $cItem['Set_ID'];
$cSetEntries = array();
}
// Store item for later
$cSetEntries[] = $cItem;
}
// Perform last set display
display_set($cSetID, count($cSetEntries));
echo ": ";
displayItemList($cSetEntries);
echo "\n";
Amusingly, it can be one single recursive function:
function displaySetList($setList, $itemList = NULL) {
// First call, start process
if ($itemList === NULL) {
$itemList = array(array_shift($setList));
displaySetList($setList, $itemList);
return;
}
// Check for display item list mode
if ($setList === false) {
// Output first entry in the list
$cItem = array_shift($itemList);
display_item($cItem['Item_ID'], $cItem['Item_Name']);
if (!empty($itemList)) {
// Output the next
echo " and ";
displaySetList(false, $itemList);
} else {
echo "\n";
}
return;
}
if (empty($setList) || $setList[0]['Set_ID'] != $itemList[0]['Set_ID']) {
// New Set detected, output set
display_set($itemList[0]['Set_ID'], count($itemList));
echo ": ";
displaySetList(false, $itemList);
$itemList = array();
}
// Add next item and carry on
$itemList[] = array_shift($setList);
displaySetList($setList, $itemList);
}
// Execute the function
displaySetList($displaySet);
Note that the recursive example here is grossly inefficient, a double loop is by far the quickest.
<?php
$sets = array();
foreach ($items as $item)
{
if (!array_key_exists($item['Set_ID'], $sets))
{
$sets[$item['Set_ID']] = array();
}
$sets[$item['Set_ID']][] = $item;
}
foreach ($sets as $setID => $items)
{
echo 'Set ' . $setID . ' has ' . count($items) . ' Items: ';
foreach ($items as $item)
{
echo $item['Item_ID'] . ' ' . $item['Item_Name'];
}
}
?>
Something like this i guess?
EDIT:
After i posted this i saw the display functions where added. But you get the point.
The need to not print out any items until we know how many there are in the set makes this difficult. At some point, we'll need to doing some buffering, or else backtracking. However, if I'm allowed internal loops, and sets are contiguous in the "master" array, then with some hacking around:
$set = 0;
$items;
foreach ($arr as $a) {
if ($a['Set_ID'] != $set) {
if ($set != 0) {
display_set($set, count($items));
foreach ($items as $i)
display_item($i)
}
$set = $a['Set_ID'];
$items = array();
}
$items[] = $a;
}
How about this:
$previous_set = false;
$items = '';
$item_count = 0;
foreach ($rows as $row)
{
if ($row['Set_ID'] != $previous_set)
{
if ($previous_set)
{
echo display_set($row['Set_ID'], $item_count);
echo $items;
}
$previous_class = $row['Set_ID'];
$item_count = 0;
$items = '';
}
$items .= display_item($row['Item_ID'], $row['Title']);
$item_count++;
}
echo display_set($row['Set_ID'], $item_count);
echo $items;

Categories