w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Nested foreach loops - anything more efficient?
You can squeeze a bit more performance from your loops by using the values by reference: foreach ($arraykey as $columnname => &$value) { Hence the &$value, but beware, every time you do something to $value after that, it will affect the original $arraykey[$columnname] value. Also, not sure you're nesting the foreach correctly. I would move the ending bracket for the nested foreach down: // $value passed by reference foreach ($arraykey as $columnname => &$value) { // Pass $field_entity_id by reference foreach ($records as &$field_entity_id) { $fieldinsertloop = "('registration', 'reg_type', 0,".$field_entity_id.",".$field_entity_id.", 'und', 0,'".$value."','".$value."')"; $sql = "INSERT INTO " .str_replace("multi_reg", "field_data", $colu

Categories : PHP

Possibilities and nested foreach loops C#
Try a recursive method. A small example : public List<Table> assignToTable(List<Person> invited, List<Table> tables) { if(!tables.HasRoom) return tables; else { assign(tables,invited) //code to add a person to a table assignToTable(invited, tables); } } If I were you I'll create a object taht represent you tables with a propertie to know if there is still some room avaiblable. This will assign to every people a table without any foreach. Then in you main you could have a method that will rearrange the tables in all the way possible : Table 1 Table 2 Table 3 Then Table 1 Table 3 Table 2 ... Table 3 Table 2 Table 1 and call the recursive method on those lists and you will have all the possibility where poeple can sit...

Categories : C#

Nested foreach loops, PHP, how do I manipulate the values?
You need to use the reference syntax (& prefix): foreach ($final_array as &$final_array_val) { } unset($final_array_val); Note that the unset is required to break the reference to the last value. Read more here.

Categories : PHP

Write nested XML file with powershell in foreach loops
using $xmlWriter.WriteEndElement() instead of $xmlWriter.WriteEndElement should fix your problem same problem in this post

Categories : Xml

nested foreach loops in R to update common array
foreach loops are used for their return value, like lapply. In this way they are very different from for loops which are used for their side effects. By using the appropriate .combine functions, the inner foreach loop can return vectors which are combined row-wise into a matrix by the outer foreach loop: x <- foreach(i=1:8, .combine='rbind') %dopar% { foreach(j=1:2, .combine='c') %do% { l <- runif(1, i, 100) i + j + l } } You can also use the nesting operator: %:%: x <- foreach(i=1:8, .combine='rbind') %:% foreach(j=1:2, .combine='c') %dopar% { l <- runif(1, i, 100) i + j + l } Note that set.seed probably won't do what you want, since it is being performed on the local machine, while the random numbers are generated in different R ses

Categories : R

Why does not the data-binding work? (using nested foreach loops)
This can't work : self.pc_listOfExpenses()[claimID] = JSON.parse(data); Because you are modifying the internal array of the observableArray(). I am not sure, but you could try this : var items = self.pc_listOfExpenses(); items[claimID] = JSON.parse(data); self.pc_listOfExpenses(items); I hope it helps.

Categories : Javascript

Why referencing in a nested ranged-based for-loops
First of all, we need to know the exact data type of int arr[10][3];. It is an array of 10 arrays of 3 int. A loop typically iterates over one dimension of a multidimensional container, e.g. for(int i = 0; i < 10; ++i) { for(int j = 0; j < 3; ++j) { arr[i][j] = 0; } } The first loop iterates over the array of 10 X, the second loop then iterates over X, which here is an array of 3 int. The next step is to explicitly use this X in code: for(int i = 0; i < 10; ++i) { int (&x)[3] = arr[i]; // you won't see this syntax often for(int j = 0; j < 3; ++j) { int &elem = x[j]; elem = 0; } } The line int (&x)[3] declares a reference to an array of 3 int, which is the result of accessing the first level of the multidi

Categories : C++

How do I create nested loops with LESS CSS?
Hm, nevermind—Found it myself. I’m leaving the answer here for posterity’s sake: @maxi: 8; .i-loop (@i) when (@i > 0) { @maxj: 8; .j-loop (@j) when (@j > 0) { .my-class-@{i}-@{j} { width: (100% / @i); height: (100% / @j); } .j-loop(@j - 1); } .j-loop (0) {} .j-loop(@maxj); .i-loop(@i - 1); } .i-loop (0) {} .i-loop(@maxi);

Categories : CSS

php foreach nested table
Here is the code I fix for you: Assuming the number of elements in $spec is same as or more than the number of elements in $tunnid. In coder's perspective, count($spec) >= count($tunnid). <table style="width: 600px" class="slicedTable"> <tr> <th>Spetsialist</th> <th>Tunnid</th> </tr> <?php $i = 0; foreach($specs as $specName => $spec): ?> <tr> <td><?php echo $specName; ?></td> <td><?php echo isset($tunnid[$i]) ? $tunnid[$i] : '-'; ?></td> </tr> <?php $i++; endforeach; ?> </table> Not really an elegant solution, I admit.

Categories : PHP

Javascript: Nested for loops to create a directory tree in VMware vCenter
Here was the solution. Apparently it was not to do with nested for loops and global objects but more to do with object reference (I still do not fully understand it). ////////////////////////////////////////////////////////////////////////////// // CODE: Javascript // // TITLE: BuildFolderTree // // AUTHOR: Brandt Winchell // // COLLABORATOR: robrtb12 // // VERSION: 1.0 // // DATE MODIFIED: June 29, 2013 // // PURPOSE: Build a directory tree in vCenter VM & Template section

Categories : Javascript

How do you create a table array using for loops?
A few things to note: For better, more concise help on the forum, post the errors you want help with also Include your code for initialization and population of your list. You initialize your array with new String[100][1];. This is the same as a 1D Array as the second dimension is 1 (i.e. 1 column), use new String[100][2]; instead. Separate the line loginsScrollPane = new JScrollPane(loginsTable = new JTable(loginTableLogins, loginTableTitles)); into loginsTable = new JTable(loginTableLogins, loginTableTitles) loginsScrollPane = new JScrollPane(loginsTable); for easier debugging.

Categories : Java

How to create a table without using methods or for-loops?
Think about it in terms of rows instead of columns. You're writing out a row at a time, not a column at a time, so look at the indices of the individual cells in the original list: | 0 | 4 | 8 | | 1 | 5 | 9 | | 2 | 6 | 10 | | 3 | 7 | 11 | Notice each row's cells' indices differ by 4. Find a simple expression for the nth row's cells and the task will become much easier, as you'll essentially be printing out a regular table.

Categories : Python

Foreach loops within a foreach loop
You could use GROUP_CONCAT. This will return a concatenated string, which you can then explode(). This will make it so you return 1 row per headline, so you can easily group your images and videos. $sql = 'SELECT headline, story, DATE_FORMAT(date, "%d-%M-%Y") AS Displaydate, name, logo, tpf_parks.park_id, GROUP_CONCAT(url) as url, GROUP_CONCAT(alt) as alt, GROUP_CONCAT(description) as description, GROUP_CONCAT(credit) as credit, GROUP_CONCAT(DISTINCT location) as location FROM tpf_news INNER JOIN tpf_parks ON tpf_news.park_id = tpf_parks.park_id LEFT JOIN tpf_images ON tpf_news.news_id = tpf_images.news_id LEFT JOIN tpf_videos ON tpf_news.news_id = tpf_videos.news_id GROUP BY tpf_images.news_id, tpf_videos.news_id ORDER BY date DESC' ; $result = $pdo->que

Categories : PHP

Avoiding nested each loops when handling nested JSON data
JSON is "just" javascript object literals. You can skip the jQuery call, and just reference the objects and arrays directly after you parse it. obj.custom_sql_rule[0].something_else[0]; of course, your JSON is a bit oddly-formed. If at all possible, don't arbitrarily mix objects {} and arrays [] . Use the latter when you have lists of identical objects or primitive data, and the former when you have named properties. And once you have a valid javascript object, you can just iterate through its properties. for(var sqlProp in jsonObj) { if(jsonObj[sqlProp].error) { errorsContainer.append("<div>" + jsonObj[sqlProp].error + "</div>"); } }

Categories : Javascript

Razor Conditional In Foreach
Are you posting the actual code? There are several problems with the one you posted, but this should work: <ul> @foreach(MenuItem item in Model.MenuItems) // No need for @ before Model inside code. { String controller = item.Controller; String activeCss = ""; if (item.IsActive) { activeCss = "active"; // Added ; here. } <li> @Html.ActionLink("Action", "Controller") // Html should not be upper-case, ActionLink requires arguments. </li> } </ul>

Categories : Misc

How to use foreach loops with while-loops
You have the definition of current_id within your loop, each iteration it will reset it to zero. You should debug this, you could quite easily add Debug.WriteLine(sb); to see the contents and you'd see that it would always return the same (note that current_id is always 0): <queryxml><entity>Account</entity><query><field>AccountNumber<expression op='greaterthan'>0</expression></field></query></queryxml> Here's updated code, which simply moves the definition of current_id out of the loop, so that it can be updated and the value will stick. bool is_finished = false; string current_id = "0"; while (is_finished == false) { sb.Append("<queryxml><entity>Account</entity><query><field>AccountNumber&l

Categories : C#

Mix of html and code in foreach in razor
Something like this should create what you need: @{ int counter = 0; foreach (var config in Model) { if (counter == 0) { @Html.Raw("<div class="row-fluid">") } else if (counter > 0 && counter % 3 == 0 ) { @Html.Raw("</div><div class="row-fluid">") } @Html.Partial("_ConfigBar", config) counter++; } @Html.Raw("</div>") } This will: create an opening div on the first loop close the current open div and open a new div on each 4th loop add a closing div once the looping is complete.

Categories : C#

mysql create table based on columns from another table and auto updated
You want to use a trigger. See: http://dev.mysql.com/doc/refman/5.6/en/triggers.html You can create the trigger so that when a row is inserted into submissions with status=true, it inserts a row into your new student table. It would look something like this: delimiter // CREATE TRIGGER sub_ins_check AFTER INSERT ON submissions FOR EACH ROW BEGIN IF NEW.status = 1 THEN INSERT INTO your_new_table (student_name, submit_date, submit_id) VALUES (NEW.student_name, NEW.submit_date, NEW.submit_id); END IF; END;// delimiter ; Then create another trigger so that when a row is updated in submissions, it updates the row with the same submit_id in your new table, like this: delimiter // CREATE TRIGGER sub_ins_check AFTER UPDATE ON submissions

Categories : Mysql

mvc razor foreach in view with sorted data
The problem has something do with your query provider; perhaps it simply doesn't support ordering. Without any further information, I'd recommend this: public IEnumerable<PercConfigEntry> GetPercConfigEntries() { var results = (from g in this.context.PercConfigEntry where g.Key == "ConfigEntries" select g) .AsEnumerable() .OrderBy(g => g.ConfigName); return results; } Or in fluent syntax: public IEnumerable<PercConfigEntry> GetPercConfigEntries() { var results = this.context.PercConfigEntry .Where(g => g.Key == "ConfigEntries") .AsEnumerable() .OrderBy(g => g.ConfigName); return results; } This forces the query to be executed on the provider without any ordering, then re-orders i

Categories : C#

Python: Using two while loops to create grid. No for loops
Conceptually, a while loop is exactly the same as a for loop, except without the increment. So if you need to implement the loop using while, you just do it as you would with for loops, but do the incrementing yourself. So this means you just nest two whiles: x = 0 table = '' while x < WIDTH: y = 0 while y < LENGTH: table += grid[WIDTH * x + y] + '|' y +=1 table += ' ' x +=1 return table

Categories : Python

Foreach loops not executing in PHP
Things you should test: Ensure $time is filled BEFORE entering the first foreach (add <?echo count($time);?> before that foreach) Ensure $week is filled BEFORE entering the second foreach (add <?echo count($week);?> before that foreach) Ensure your query is returning anything. (Print out the generated query string, and execute it with some database software like phpmyadmin.) If you have performed this 3 steps, you have found the problem, and can solve it.

Categories : PHP

Two foreach loops to be used in one SQL query
$itempack = mysql_query("SELECT * FROM db WHERE ItemLevel BETWEEN $formlevel1 AND $formlevel2 AND InventoryType = in ('". implode("', '", $slotarray) ."') AND Quality<5 AND AllowableClass in ('$formclass', '-1','2047','32767') AND Material = in ('". implode("', '", $armortype) ."') ORDER BY RAND() LIMIT 1"); That should do it. Place it instead of both loops. It simply runs only one query instead of dozens of it...

Categories : PHP

PHP - foreach loops - $arr and &$value as same variable
No, they cannot be the same variable; $foo would be an array and &$bar would be the reference to an element of that array. That's why it's called a for-each loop, because it's looping through the elements of an array and, in this case, modifying them directly (because you are using references).

Categories : PHP

Let user create table based on existing table
It is possible. Firstly, read from the "existing" db table to create the select menu, example: <select name="item"> <?php $sql = "SELECT * FROM existing"; $query = mysqli_query($mysqli, $sql); while ($result = mysqli_fetch_array($query)) { $item = $result['item']; echo "<option value='$item'>$item</option>"; } ?> </select> This will create the "Item" select menu, I'm sure you can figure out how to do the other menus by yourself, all that is left now is to submit and store into the new table which I assume you already know how to do. if(isset($_POST['yoursubmitname'])) { $item = $_POST['item']; /// RUN THE INSERT COMMAND HERE // }

Categories : PHP

Get Ajax variable from the PHP foreach loops
// get field values $qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"]; Instead of using both $_GET and $_POST, you can use $_REQUEST which will give data from either POST or GET.

Categories : PHP

c:forEach runs always the same amount of loops
The <c:forEach> runs during view build time (that moment when XHTML is turned into JSF component tree), while the <ui:repeat> runs during view render time (that moment when JSF component tree produces HTML output). So, when the <c:forEach> runs, the #{entityDepthHolder} is nowhere available in the EL scope and evaluates to null and in this case implicitly coerced to 0. As the begin is also 0 and the end is inclusive, you effectively end up with 1 item. After the view build time, the JSF component tree ends up like this: <ui:repeat value="#{myHandler.entityTree}" var="entityDepthHolder"> <p:commandLink action="#{myHandler.toggle(entityDepthHolder.entity)}"> <div> <span class="intendWidth" /> #{entityDepthHolde

Categories : JSF

Memory allocation when using foreach loops in C#
Because an enumerator keeps hold of the current item. It's like a cursor compared to databases. If multiple threads would access the same enumerator, you would lose control of the sequence. And you would have to reset it to the first item every time a foreach consults it.

Categories : C#

Foreach loops and array problems
In your code you're overwriting the $array data over and over again on each loop iteration. $array = array('groups' => array()); // creating empty array of groups, just once foreach($permnode as $perm){ if (!isset($array['groups'][$groupname])) { // if the group with a particular // name doesn't exist yet // then creating it and initializing with empty permissions array $array['groups'][$groupname] = array('permissions' => array()); } // here is where you was wrong: instead of overwriting the whole array // with new data - you're just adding another item into permissions array $array['groups'][$groupname]['permissions'][$perm] = true; }

Categories : PHP

Efficiency between searching and foreach loops
Implement the easiest one. Do not worry about optimization until you have metrics to support the need. If it is not fast enough/efficient enough, then get some good time measurements. Now it is time to consider alternate implementations. Implement and time each of the alternates, picking the fastest/most efficient one.

Categories : C#

perform two foreach loops on same data
Use an ArrayIterator, per the docs: When you want to iterate over the same array multiple times you need to instantiate ArrayObject and let it create ArrayIterator instances that refer to it either by using foreach or by calling its getIterator() method manually. And the example follows: <?php $fruits = array( "apple" => "yummy", "orange" => "ah ya, nice", "grape" => "wow, I love it!", "plum" => "nah, not me" ); $obj = new ArrayObject( $fruits ); $it = $obj->getIterator(); // How many items are we iterating over? echo "Iterating over: " . $obj->count() . " values "; // Iterate over the values in the ArrayObject: while( $it->valid() ) { echo $it->key() . "=" . $it->current() . " "; $it->next(); } // The good thing her

Categories : PHP

Avoid multiple foreach loops
You may try to use array_map instead of foreach: $user_ids = array_map(function($obj){ return $obj->user_id; }, $array); NOTE: This example requires at least PHP 5.3, as it was implemented with anonymous functions. As the benchmark shows, native foreach-loop is faster than array_map. It is more efficient, as it is a native language construction. If ignore this fact, other cycle constructions (while, for) or array_map are the only way. But it would be really better, if you reconstruct your query, to execute it without php-processing. There are a lot of functionality like INNER JOIN, LEFT JOIN, subqueries, loops and stored procedures. It might be really faster.

Categories : PHP

Turning foreach loops to Linq
does using linq expressions instead of foreach loop speed up the performance of the program, I'm kind of new to this linq. No. Internally, LINQ will still typically perform the same number of iterations, so in general, it won't speed things up. Written properly, LINQ will perform very similarly to the looping. It is very useful to make the intent more clear, which in turn can sometimes make it simpler to optimize and short curcuit. That being said, those same optimizations can be done on loops just as easily. Is there anyway to write turn this for each loop into Linq expression: Yes. This could be done via: foreach(var item in this.datasetItemset .SelectMany(transaction => transaction.Split(' ')) .Distinct()) { itemList.Add(item); itemsetScanning.Add(item

Categories : C#

R foreach loops on 3D array data
When parallelizing computations, because of the overhead it introduces, it is preferable to run large pieces of computations in parallel, rather than small -- outer loops, rather than inner loops. In this case, however, there is no need to parallelize the computations: you can just vectorize them. # 3-dimensional analogue of row() and col() dim3 <- function( a, i ) { stopifnot( length(dim(a)) == 3 ) r <- a if( i == 1 ) { r[] <- rep(1:dim(a)[1], dim(a)[2] * dim(a)[3]) } if( i == 2 ) { r[] <- rep(1:dim(a)[2], each = dim(a)[1], times = dim(a)[3]) } if( i == 3 ) { r[] <- rep(1:dim(a)[3], each = dim(a)[1] * dim(a)[2]) } r } probability_array <- array(0,dim=c(length(xvox),length(yvox),length(zvox))) i <- dim3(probability_array,1) j <- dim3(probability_

Categories : R

programmatic defined # foreach loops c#
If you have one array with three items in it, then in order to enumerate through the items you should only need one foreach loop. List<Object> items = new List<Object> { Universe, Earth, Continent }; foreach (var item in items) { ... } You would only need to write additional nested foreach loops if the objects contained by the outer array each themselves implemented IEnumerable, and you needed to enumerate these as well. Without seeing the problem that you are trying to solve, it is hard to make a recommendation. But I think that the assumption that you need to have nested foreach structures is incorrect.

Categories : C#

How to create custom control in mvc 4 razor view which is pluggable to another mvc 4 razor view projects
There's a post here on using the Razor File Generator, which addresses the same issue as you have http://blogs.msdn.com/b/davidebb/archive/2010/10/27/turn-your-razor-helpers-into-reusable-libraries.aspx The project is in codeplex, so you can get the Source Code and the Documentation any any other information from here.

Categories : Asp Net Mvc

Group radio buttons in foreach loop in MVC razor view?
Use simple RadioButton <ol class="Opt"> @foreach (var opt in quest.Options) { <li class="Opt"> @Html.RadioButton("uniqueRadio", opt.Title) @Html.Label(opt.Title) </li> } </ol

Categories : Asp Net Mvc

Element naming convention in Razor generator within a foreach loop
in short, use a for loop instead of a foreach loop (see the answer here). You need to manually index it MVC Razor view nested foreach's model EDIT: added sample code @for(int i=0; i < Model.ListTwo.Count; i++) { @Html.HiddenFor(t => t.ListTwo[i].Id) } Okay, for collections that inherit from ICollection, try @for (int i = 0; i < Model.CollectionThree.Count; i++) { @Html.Hidden("CollectionThree[" + i + "].Id", Model.CollectionThree.ElementAt(i).Id) } Another edit: To avoid using the property name, you could do something like @for (int i = 0; i < Model.CollectionThree.Count; i++) { @Html.Hidden(Html.NameFor(t => Model.CollectionThree) + "[" + i + "]." + Html.NameFor(t =>Model.CollectionThree.ElementAt(i).Id) ,Model.Coll

Categories : Asp Net Mvc

Struct casting behavior different between for and foreach loops
Iterating a Hashtable doesn't iterate its values, rather it iterates key value pairs as a DictionaryEntry object. Instead try iterating on its .Values collection instead. foreach (var item in hashtable.Values) { var myStruct = (MyStruct)item; } Since you are refactoring old legacy code, if possible, you should also consider using the generic Dictionary<TKey, TValue> instead. It will take advantage of struct value semantics and avoid boxing. If you wanted to iterate on the DictionaryEntry objects, you can do so but will need to cast to it as well as your MyStruct: foreach (DictionaryEntry entry in hashtable) { var myStruct = (MyStruct)entry.Value; } Finally, there's the Linq solution, but it may not be applicable for you since this is legacy code; it may not be ava

Categories : C#

Perl - How to do two different Foreach loops without having to duplicate code
First of all, defined @array and defined %hashofarrays is wrong. They are always defined. You want if (@array) and if (keys %hashofarrays) to test if they contain elements. You should have even gotten an warning defined(@array) is deprecated! What you want is another subroutine. sub loop_body { # just use some better name! my ($var) = @_; call_subroutine($var); print "Something else is printed"; call_anothersubroutine($var); call_differentsubroutine($var); } Then: if (@array) { foreach my $var1 (@array) { print "var1 is: $var1 "; loop_body($var1); } } elsif (keys %hashofarrays) { foreach my $key (keys %hashofarrays) { print "the key is: $key "; foreach my $var1 (@{$hashofarrays{$key}}) { loop_body($var1) }

Categories : Perl

PHP - How to assign string key and value for array within 2 foreach loops?
$imgs = array_combine($img_thumbs, $img_links); See http://php.net/array_combine If you absolutely wanted to do that in a loop: foreach ($img_thumbs as $i => $thumb) { $imgs[$thumb] = $img_links[$i]; }

Categories : PHP



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.