Search Results

Search found 4868 results on 195 pages for 'foreach'.

Page 3/195 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • MonoTouch - foreach vs for loops (performance)

    - by ifwdev
    Normally I'm well aware that a consideration like this is premature optimization. Right now I have some event handlers being attached inside a foreach loop. I am wondering if this style might be prone to leaks or inefficient memory use due to closures being created. Is there any validity to this thinking?

    Read the article

  • foreach: how to iterate this

    - by ilnur777
    object(stdClass)[1] public 'inbox' => array 0 => object(stdClass)[2] public 'from' => string '55512351' (length=8) public 'date' => string '29/03/2010' (length=10) public 'time' => string '21:24:10' (length=8) public 'utcOffsetSeconds' => int 3600 public 'recipients' => array 0 => object(stdClass)[3] public 'address' => string '55512351' (length=8) public 'name' => string '55512351' (length=8) public 'deliveryStatus' => string 'notRequested' (length=12) public 'body' => string 'This is message text.' (length=21) 1 => object(stdClass)[4] public 'from' => string '55512351' (length=8) public 'date' => string '29/03/2010' (length=10) public 'time' => string '21:24:12' (length=8) public 'utcOffsetSeconds' => int 3600 public 'recipients' => array 0 => object(stdClass)[5] public 'address' => string '55512351' (length=8) public 'name' => string '55512351' (length=8) public 'deliveryStatus' => string 'notRequested' (length=12) public 'body' => string 'This is message text.' (length=21) .... .... I have this foreach, but it does not iterate address, name, deliveryStatus! Could you show how to get this data? foreach ($data->inbox as $note) { echo '<p>'; echo 'From : ' . htmlspecialchars($note->from) . '<br />'; echo 'Date : ' . htmlspecialchars($note->date) . '<br />'; echo 'Time : ' . htmlspecialchars($note->time) . '<br />'; echo 'Body : ' . htmlspecialchars($note->body) . '<br />'; }

    Read the article

  • php foreach getting values from an array

    - by sea_1987
    I am having trouble accessing the values in an array, the array looks like this, Array ( [0] => Array ( [id] => 1661 [code] => 849651318 [job_status] => 4 [looking_for] => Lorem ipsum [keywords_education] => Derby University [sector_id_csv] => 10,21,9,22,26 [last_job_title_1] => Programmer [last_job_employer_1] => HBOS [city] => Bury [expected_salary_level] => LEVEL_2 [education_level] => COLLEGE [job_looking_for] => [is_contract] => Y [is_permanent] => N [is_temporary] => Y ) ) Array ( [0] => Array ( [id] => 402 [code] => 849650059 [job_status] => 3 [looking_for] => Lorem ipsum [keywords_education] => Paris College [sector_id_csv] => 27,22,19,21,12 [last_job_title_1] => Programmer [last_job_employer_1] => HSBC [city] => Bury [expected_salary_level] => LEVEL_2 [education_level] => COLLEGE [job_looking_for] => [is_contract] => N [is_permanent] => Y [is_temporary] => Y ) ) Array ( [0] => Array ( [id] => 1653 [code] => 849651310 [job_status] => 3 [looking_for] => Lorem ipsum [keywords_education] => Crewe University [sector_id_csv] => 27,15,19,21,24 [last_job_title_1] => Programmer [last_job_employer_1] => ICI [city] => Bury [expected_salary_level] => LEVEL_2 [education_level] => UNIVERSITY [job_looking_for] => [is_contract] => N [is_permanent] => Y [is_temporary] => Y ) ) I am trying to get the values out, I have tried doing the following, foreach ($result as $rslt) { echo $rslt->id; } I have also tried, foreach ($result as $rslt) { $rslt['id']; } But none of this works, I dont know why, can anyone help?

    Read the article

  • C# - Does foreach() iterate by reference?

    - by sharkin
    Consider this: List<MyClass> obj_list = get_the_list(); foreach( MyClass obj in obj_list ) { obj.property = 42; } Is 'obj' a reference to the corresponding object within the list so that when I change the property the change will persist in the object instance once constructed somewhere?

    Read the article

  • Combining foreach and using

    - by apoorv020
    I'm iterating over a ManageObjectCollection.( which is part of WMI interface). However the important thing is, the following line of code. : foreach (ManagementObject result in results) { //code here } The point is that ManageObject also implements IDisposable, so I would like to put "result" variable in a using block. Any idea on how to do this, without getting too weird or complex?

    Read the article

  • How to optimize foreach loop in PHP

    - by vanneto
    First off, I know the title is generic and not fitting. I just couldn't think of a title that could describe my problem. I have a table Recipients in MySQL structured like this: id | email | status 1 foo@bar S 2 bar@baz S 3 abc@def R 4 sta@cko B I need to convert the data into the following XML, depending on the status field. For example: <Recipients> <RecipientsSent> <!-- Have the 'S' status --> <recipient>foo@bar</recipient> <recipient>bar@baz</recipient> </RecipientsSent> <RecipientsRegexError> <recipient>abc@def</recipient> </RecipientsRegexError> <RecipientsBlocked> <recipient>sta@cko</recipient> </RecipientsBlocked> </Recipients> I have this PHP code to implement this ($recipients contains an associative array of the db table): <Recipients> <RecipientsSent> <?php foreach ($recipients as $recipient): if ($recipient['status'] == 'S'): echo "<recipient>" . $recipient['email'] . "</recipient>"; endif; endforeach; ?> </RecipientsSent> <RecipientsRegexError> <?php foreach ($recipients as $recipient): if ($recipient['status'] == 'R'): echo "<recipient>" . $recipient['email'] . "</recipient>"; endif; endforeach; ?> </RecipientsRegexError> <?php /** same loop for the B status */ ?> </Recipients> So, this means that if I have 1000 entries in the table and 4 different status' that can be checked, it means that there will be 4 loops, each one executing 1000 times. How can this be done in a more efficient manner? I thought about fetching four different sets from the database, meaning 4 different queries, would that be more efficient? I'm thinking it could be done with one loop but but I can't come up with a solution. Any way this could be done with only one loop?

    Read the article

  • Generic foreach loop in C#.

    - by mcoolbeth
    The compiler, given the following code, tells me "Use of unassigned local variable 'x'." Any thoughts? public delegate Y Function<X,Y>(X x); public class Map<X,Y> { private Function<X,Y> F; public Map(Function f) { F = f; } public Collection<Y> Over(Collection<X> xs){ List<Y> ys = new List<Y>(); foreach (X x in xs) { X x2 = x;//ys.Add(F(x)); } return ys; } }

    Read the article

  • Removing last word from FOREACH loop

    - by Stoosh
    I'm building a basic function, which builds out Mysql WHERE clauses based on how many are in the array. $array = array('id' => '3', 'name' => 'roger'); $sql = "SELECT * FROM table WHERE "; foreach ($array as $k => $v) { $sql .= $k . ' = ' . $v . ' AND '; } which will output SELECT * FROM table WHERE id = 3 AND name = roger AND However obviously I don't want that last AND, how do I go about removing it from the string? Thanks

    Read the article

  • Foreach loop is running n times

    - by Furqan Khyraj
    foreach($CarAdList as $CarAd) { echo($msg .= '<tr><td>'.$CarAd->getCarAdID().'</td><td>' .$CarAd->getBrandText().'</td><td>' .$CarAd->getDescription(). '</td><td><a href="status.php?id='.$CarAd->getCarAdID().'"><img src="../images/active.png" /></a></td><td><img src="../images/delete.png" width="30px" /></td></tr>'); } e.g, the number of rows =38 n= the number of rows * the number of rows-- it is running n times so its displaying 5 5 4 5 4 3 5 4 3 2 5 4 3 2 1

    Read the article

  • Foreach File in a Folder in Flash?

    - by msandbot
    Hey, I have an image slideshow program working right now and it takes in a folder of a hard coded in number of images. I would like to change this so that it can take in a folder and will display all of them no matter the number. Is there a way to do this in flash? I'm thinking something like the foreach loop in perl or other scripting language. It is possible to store then number of images in a text file but I also don't know how to read that in flash either. I'm working in actionscript 3. Any help would be greatly appreciated. Thanks -Mike

    Read the article

  • jQuery toggle on a PHP foreach statement

    - by user313835
    The code for the page is the following <?php foreach ($organization->index() as $id=>$content) { ?> <a href="#" id="obtain_branch"><?= $content->name?></a> <div id="directory_brnach"><?= $content->about?></div> <?php } ?> The JavaScript code using jQuery is // Directory inner branches $('#obtain_branch').click(function(){ $('#directory_brnach').toggle('fast'); }); The problem it will only work on the first one given the the ID is not changing, the rest will not change. How can I send an array to the jQuery function to give an individual ID on every iteration? Thanks in advance.

    Read the article

  • foreach with an array of stdclass objects

    - by Jared Steffen
    So, what I want to do is quite simple in my mind. I have an array that consists solely of four objects. I want to create a loop that will echo an attribute of each object in the array. The only success I've had, however, is echoing every object and every property of the objects. I've never dealt with objects so this is probably the TRUE root of the problem. There's been a few revisions but the only thing I've really excelled at is creating error codes. Here is what I have: $categories = get_categories(array('child_of' => '8')); foreach ($categories as $cat) { echo $cat->name; };

    Read the article

  • php foreach looping twice

    - by Jack
    Hi, I am trying to loop through some data from my database but it is outputting it twice. $fields = 'field1, field2, field3, field4'; $idFields = 'id_field1, id_field2, id_field3, id_field4'; $tables = 'table1, table2, table3, table4'; $table = explode(', ', $tables); $field = explode(', ', $fields); $id = explode(', ', $idFields); $str = 'Egg'; $i=1; while ($i<4) { $f = $field[$i]; $idd = $id[$i]; $sql = $writeConn->select()->from($table[$i], array($f, $idd))->where($f . " LIKE ?", '%' . $str . '%'); $string = '<a title="' . $str . '" href="' . $currentProductUrl . '">' . $str . '</a>'; $result = $writeConn->fetchAssoc($sql); foreach ($result as $row) { echo 'Success! Found ' . $str . ' in ' . $f . '. ID: ' . $row[$idd] . '.<br>'; } $i++; } Outputting: Success! Found Egg in field3. ID: 5. Success! Found Egg in field3. ID: 5. Could someone please explain why it is looping through both the indexed and associative values? UPDATE I did some more playing around and tried the following. $fields = 'field1, field2, field3, field4'; $idFields = 'id_field1, id_field2, id_field3, id_field4'; $tables = 'table1, table2, table3, table4'; $table = explode(', ', $tables); $field = explode(', ', $fields); $id = explode(', ', $idFields); $str = 'Egg'; $i=1; while ($i<4) { $f = $field[$i]; $idd = $id[$i]; $sql = $writeConn->select()->from($table[$i], array($f, $idd))->where($f . " LIKE ?", '%' . $str . '%'); $string = '<a title="' . $str . '" href="' . $currentProductUrl . '">' . $str . '</a>'; $sth = $writeConn->prepare($sql); $sth->execute(); $result = $sth->fetch(PDO::FETCH_ASSOC); foreach ($result as $row) { echo 'Success! Found ' . $str . ' in ' . $f . '. ID: ' . $row[$idd] . '.<br>'; } $i++; } The interesting thing is that this outputs the below: Success! Found Egg in field3. ID: E. Success! Found Egg in field3. ID: E. Success! Found Egg in field3. ID: 5. Success! Found Egg in field3. ID: 5. Success! Found Egg in field3. ID: E. Success! Found Egg in field3. ID: E. Success! Found Egg in field3. ID: 5. Success! Found Egg in field3. ID: 5. I have also tried adding $i to the output and this outputs 2 as expected. If I change fetch(PDO::FETCH_BOTH) to fetch(PDO::FETCH_ASSOC) the output is as follows: Success! Found Egg in field3. ID: E. Success! Found Egg in field3. ID: E. Success! Found Egg in field3. ID: 5. Success! Found Egg in field3. ID: 5. This has been bugging me for too long, so if anyone could help I would be very appreciative!

    Read the article

  • Problem with anonymouse delegate within foreach

    - by geting
    public Form1() { InitializeComponent(); Collection<Test> tests = new Collection<Test>(); tests.Add(new Test("test1")); tests.Add(new Test("test2")); foreach (Test test in tests) { Button button = new Button(); button.Text = test.name; button.Click+=new EventHandler((object obj, EventArgs arg)=>{ this.CreateTest(test); }); this.flowLayoutPanel1.Controls.Add(button); } } public void CreateTest(Test test) { MessageBox.Show(test.name); } } when i click the button witch text is 'test1', the messagebox will show 'test2',but my expect is 'test1'. So ,would anyone please tell me why or what`s wrong with my code.

    Read the article

  • Wrapping 3 objects or less inside a while / foreach in PHP

    - by DarkGhostHunter
    Simple question. I have an array of 21 elements, and show every three of them inside a <div> block. The code is something like this: <?php $faces= array( 1 => 'happy', 2 => 'sad', (sic) 21 => 'angry' ); $i = 1; foreach ($faces as $face) { echo $face; $i++; } ?> The problem lies when this array doesn't have 21 elements, sometimes it gets 24, an other times 17. How I wrap every three of them, and wrap alone the rest? I came up with using switch and case, but that works only when there are 21 elements only. I think I could count them beforehand and put a closing in the last one (even if it is a group of one element).

    Read the article

  • Action(Of T) in Visual Basic in List(Of T).ForEach

    - by Jason
    I have searched high and low for documentation on how to use this feature. While the loop I could write would be simple and take no time, I really would like to learn how to use this. Basically I have a class, say, Widget, with a Save() sub that returns nothing. So: Dim w as New Widget() w.Save() basically saves the widget. Now let's say I have a generic collection List(Of Widget) name widgetList(Of Widget) and I want to run a Save() on each item in that list. It says I can do a widgetList.ForEach([enter Action(Of T) here]) ....but how in the F does this work??? There is no documentation anywhere on the intrablags. Help would be much much appreciated.

    Read the article

  • asp.net mvc radioButtonFor in forEach

    - by George
    Does anyone know why this isn't working? any source code changes would be great. <% foreach (var i in Model.talentImages) { %> <div style="padding:15px;"> <img src="<%: i.uri %>" width="95" height="84" alt="" style="float:left; padding:0px 20px 0px 0px" /> <div style="padding:30px 10px 10px 10px"> <%: Html.RadioButtonFor("group-" + i.uriId.ToString(), i.isApproved)%> Approved <br /> <%: Html.RadioButtonFor("group-" + i.uriId.ToString(), i.isApproved)%> Deny <br /> </div> <hr width="0"/> <%= Html.RadioButton("isProfileePicGroup", i.isProfilePic, false)%> Make Profile Picture <br /> </div> <hr /> <%} %>

    Read the article

  • PHP foreach help

    - by sea_1987
    Hello I have an array that looks like this, Array ( [cfi_title] => Mr [cfi_firstname] => Firstname [cfi_surname] => Lastname [cfi_email] => [email protected] [cfi_subscribe_promotional] => [cfi_tnc] => [friendsName] => Array ( [0] => Firstname 1 [1] => Firstname 2 [2] => Firstname 3 ) [friendsEmail] => Array ( [0] => [email protected] [1] => [email protected] [2] => [email protected] ) [submit_form] => Submit ) My dilema is I need to save the values from the friendsName and friendsEmail arrays into a database, I know I can loop through them but how can I send the matching data, for example I need to save [friendsName][0] and friendsEmail][0] on the same row of database? I know I need to use a foreach but I just cannot figure out the logic.

    Read the article

  • A loop (while/foreach) with "offset" wrapping and

    - by DarkGhostHunter
    After applying what wrapping objects using math operator, I just tought it will be over. But no. By far. <?php $faces= array( 1 => '<div class="block">happy</div>', 2 => '<div class="block">sad</div>', (sic) 21 => '<div class="block">angry</div>' ); $i = 1; foreach ($faces as $face) { echo $face; if ($i == 3) echo '<div class="block">This is and ad</div>'; if ($i % 3 == 0) { echo "<br />"; // or some other wrapping thing } $i++; } ?> In the code I have to put and ad after the second one, becoming by that the third object. And then wrap the three all in a <div class="row"> (a br after won't work out by design reasons). I thought I will going back to applying a switch, but if somebody put more elements in the array that the switch can properly wrap, the last two remaining elements are wrapped openly. Can i add the "ad" to the array in the third position? That would make things simplier, only leaving me with guessing how to wrap the first and the third, the fourth and the sixth, an so on.

    Read the article

  • Selenium navigation inside foreach loop

    - by smudgedlens
    I am having an issue with navigation. I get a list of rows from an html table. I iterate over the rows and scrape information from them. But there is also a link on the row that I click to go to more information related to the row to scrape. Then I navigate back to the page with the original table. This works for the first row, but for the subsequent rows, it throws an exception. I look at my row collection after the first time the link inside a row is clicked, and none of them have the correct values like they did before I clicked the link. I believe that there is something going on when I navigate to a different URL that I'm not getting. My code is below. How do I get this working so I can iterate over the parent table, click the links in each row, navigate to the child table, but still continue iterating over the rows in the parent table? private List<Document> getResults() { var documents = new List<Document>(); //Results IWebElement docsTable = this.webDriver.FindElements(By.TagName("table")) .Where(table => table.Text.Contains("Document List")) .FirstOrDefault(); var validDocRowRegex = new Regex(@"^(\d{3}\s+)"); var docRows = docsTable.FindElements(By.TagName("tr")) .Where(row => //It throws an exception with .FindElement() when there isn't one. row.FindElements(By.TagName("td")).FirstOrDefault() != null && //Yeah, I don't get this one either. I negate the match and so it works?? !validDocRowRegex.IsMatch( row.FindElement(By.TagName("td")).Text)) .ToList(); foreach (var docRow in docRows) { //Todo: find out why this is crashing on some documents. var cells = docRow.FindElements(By.TagName("td")); var document = new Document { DocID = Convert.ToInt32(cells.First().Text), PNum = Convert.ToInt32(cells[1].Text), AuthNum = Convert.ToInt32(cells[2].Text) }; //Go to history for the current document. cells.Where(cell => cell.FindElements(By.TagName("a")).FirstOrDefault() != null) .FirstOrDefault().Click(); //Todo: scrape child table. this.webDriver.Navigate().Back(); } return documents; }

    Read the article

  • PHP - Parse XML subitems using foreach()

    - by Nate Shoffner
    I have an XML file that needs parsing in PHP. I am currenlty using simplexml_load_file to load the file like so: $xml = simplexml_load_file('Project.xml'); Inside that XML file lies a structure like this: <?xml version="1.0" encoding="ISO-8859-1"?> <project> <name>Project 1</name> <features> <feature>Feature 1</feature> <feature>Feature 2</feature> <feature>Feature 3</feature> <feature>Feature 4</feature> </features> </project> What I am trying to do is print the <name> contents along with EACH <feature> element within <features>. I'm not sure how to do this because there is more than 1 element called <feature>. Any help is greatly appreciated.

    Read the article

  • Boost ForEach Question

    - by bobber205
    Trying to use something like the below with a char array but it doesn't compile. But the example with short[] works fine. Any idea why? :) char someChars[] = {'s','h','e','r','r','y'}; BOOST_FOREACH(char& currentChar, someChars) { } short array_short[] = { 1, 2, 3 }; BOOST_FOREACH( short & i, array_short ) { ++i; }

    Read the article

  • An observation on .NET loops – foreach, for, while, do-while

    It’s very common that .NET programmers use “foreach” loop for iterating through collections. Following is my observation whilst I was testing simple scenario on loops. “for” loop is 30% faster than “foreach” and “while” loop is 50% faster than “foreach”. “do-while” is bit faster than “while”. Someone may feel that how does it make difference if I’m iterating only 1000 times in a loop. This test case is only for simple iteration. According to the "Data structure" concepts, best and worst cases are completely based on the data we provide to the algorithm. so we can not conclude that a "foreach" algorithm is not good. All I want to tell that we need to be little cautious even choosing the loops. Example:- You might want to chose quick sort when you want to sort more numbers. At the same time bubble sort may be effective than quick sort when you want to sort less numbers. Take a simple scenario, a request of a simple web application fetches the data of 10000 (10K) rows and iterating them for some business logic. Think, this application is being accessed by 1000 (1K) people simultaneously. In this simple scenario you are ending up with 10000000 (10Million or 1 Crore) iterations. below is the test scenario with simple console application to test 100 Million records. using System;using System.Collections.Generic;using System.Diagnostics;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { var sw = new Stopwatch(); var numbers = GetSomeNumbers(); sw.Start(); foreach (var item in numbers) { } sw.Stop(); Console.WriteLine( String.Format("\"foreach\" took {0} milliseconds", sw.ElapsedMilliseconds)); sw.Reset(); sw.Start(); for (int i = 0; i < numbers.Count; i++) { } sw.Stop(); Console.WriteLine( String.Format("\"for\" loop took {0} milliseconds", sw.ElapsedMilliseconds)); sw.Reset(); sw.Start(); var it = 0; while (it++ < numbers.Count) { } sw.Stop(); Console.WriteLine( String.Format("\"while\" loop took {0} milliseconds", sw.ElapsedMilliseconds)); sw.Reset(); sw.Start(); var it2 = 0; do { } while (it2++ < numbers.Count); sw.Stop(); Console.WriteLine( String.Format("\"do-while\" loop took {0} milliseconds", sw.ElapsedMilliseconds)); } #region Get me 10Crore (100 Million) numbers private static List<int> GetSomeNumbers() { var lstNumbers = new List<int>(); var count = 100000000; for (var i = 1; i <= count; i++) { lstNumbers.Add(i); } return lstNumbers; } #endregion Get me some numbers }} In above example, I was just iterating through 100 Million numbers. You can see the time to execute various  loops provided in .NET Output "foreach" took 1108 milliseconds "for" loop took 727 milliseconds "while" loop took 596 milliseconds "do-while" loop took 594 milliseconds   Press any key to continue . . . So I feel we need to be careful while choosing the looping strategy. Please comment your thoughts. span.fullpost {display:none;}

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >