FAQ Database Discussion Community


Modify a value in a foreach to change another one

javascript,php,foreach,textbox,value
I've got a question about this foreach loop: foreach ($result as $row) { $html.='<tr> <td>'.$row['product_name'].'</td> <td>'.recupHourMinSec($row['date_add']).'</td> <td><input type="text" name="preparationTime" id="preparationTime" value="15" /></td> <td>'.date('H:i:s', strtotime("+$preparationTime mins".$row['date_add'])).'</td> <td>'.$row['lastname'].' '.$row['firstname'].'</td> <td>'.$row['phone'].'</td>...

Create array of arrays with dynamic names

javascript,arrays,foreach
I want to create array for each user and store them in another array. For that I used this code: var arrs = []; var userCount = 1; @foreach($eventUsers as $user) { arrs['arr' + userCount] = []; userCount++; } and console.log(arrs); gave me the output [arr1: Array[0], arr2: Array[0], arr3:...

For-Each Loop Alternative - Clarification

java,loops,foreach,iterator
I am working through lessons in Java, and have not been able to completely understand what is going on in the following lesson. Purpose: The purpose of this lesson is to explain how a for-each loop works by creating an alternative that simulates how the for-each loop would work. In...

Collect strings after a foreach loop

c#,xml,foreach
Is it possible to collect the strings after a foreach loop? For example: StringCollection col = new StringCollection(); XmlNodeList skillNameNodeList=SkillXML.GetElementsByTagName("name"); foreach (XmlNode skillNameNode in skillNameNodeList) { skillsName=skillNameNode.Attributes["value"].Value; } col.Add(skillsName); //Return System.Collections.Specialized.StringCollection I want to collect each skillsName and put them in a collection or a list so that I can...

Format Excel worksheets using for each loop VBA

vba,foreach
I have a workbook with 3 sheets. I would like to format each sheet the same using VBA (set font size, auto fit columns, sort). I found a piece of code to loop through the sheets: Sub wsLoop() ' Declare Current as a worksheet object variable. Dim ws As Worksheet...

PHP foreach and continue [closed]

php,loops,foreach
I've come across a function in some code I'm trying to debug and I'm not sure why it is written like this foreach ($companies as $company) { if (!isset($company->account)) { continue; } some_function($company, $sectorsMap, $subSectorsMap); } Is this the same? foreach ($companies as $company) { if (!isset($company->account)) { some_function($company, $sectorsMap,...

Assign foreach variables

php,html,arrays,foreach
I've tried, believe me I've tried to figure this out but for the best part of the day it has beaten me so I have to ask this question: I have a list ($list) of 100 words which I have put into an array: foreach ($tag_array as $key => $names...

calling internal method for each object in an array

javascript,arrays,foreach,callback
I have a "class" with properties and methods. And I have instances of that class in an array in some other place in the code. Now I want to iterate through all of them and for each call a method. Something like this: arr.forEach(draw()); But of course it looks up...

How to stop foreach loop from printing duplicate data?

php,csv,foreach
I am trying to generate unique CSV files from the csv data that I have using the following loop. $k =1; foreach ($csv_tbl as $_csv) { $filename = "Agent_" . $k . ".csv"; $file_path = "agents/$filename"; file_put_contents($file_path, $_csv); if (file_exists($_csv)) { header('Content-Description: File Transfer'); header('Content-type: text/csv'); header('Content-Disposition: attachment; filename=' ....

TCPDF - loop data in two columns layout

php,foreach,tcpdf
Im using TCPDF, at the moment im a listing data in two columns using array_chunk which works fine. But i need data to be show in first columns and then second, see below: Currently: 1 2 3 4 5 6 7 8 9 10 Should be: 1 6 2 7...

using “foreach” for running different classifiers in R

r,foreach,parallel-processing
I am trying to use foreach to run different classifiers on my data, but it doesn't work. In fact it doesn't return me anything. my purpose is to parallelize my process. here is the simplified of my code: library(foreach) library(doParallel) no_cores <- detectCores() - 1 cl<-makeCluster(no_cores) registerDoParallel(cl) registerDoParallel(no_cores) model_list<-foreach(i =...

How do I throw an Exception from inside a Parallel.ForEach loop?

c#,foreach,exception-handling,parallel-processing
I have a Parallel.Foreach loop which downloads files like so: try { var parallelOptions = new ParallelOptions(); parallelOptions.MaxDegreeOfParallelism = 8; int failedFiles = 0; Parallel.ForEach(FilesToDownload, parallelOptions, tile => { bool downloaded = DownloadTile(File); if (downloaded) { //Downloaded :) } else { failedFiles++; if (failedFiles > 10) { throw new Exception("10...

How can I group my array into groups of 3 elements, sort them by the last element and display the elements?

php,arrays,sorting,foreach
I'm trying to display my array in groups of 3 elements, sorted by the last element of each group. My array: $info = array('goal','raul','80','foul','moneer','20','offside','ronaldo','60'); My expected output is: 1-foul moneer 20 2-offside ronaldo 60 3-goal raul 80 Sorted by the last value of the element groups. I'm using foreach to...

Use a foreach within a new object declaration

c#,arrays,linq,list,foreach
So I am working with an api response and I have the following code: if (!string.IsNullOrEmpty(json)) { var resources = (JArray) JsonConvert.DeserializeObject(json); var itemStore = resources.Select(r => new ItemObject { Id = r["Id"].ToString(), Title = r["title"].ToString(), LongDescription = r["longDescription"].ToString(), ShortDescription = r["shortDescription"].ToString(), ChildItems = ??? }).ToList(); } So, where the...

Creating a sequence of unique random digits

arrays,perl,foreach,unique
I have the following code use strict; use warnings; use 5.22.0; # Generating random seed using # Programming Perl p. 955 srand( time() ^ ($$ + ($$ << 15 ) ) ); # Generating code that could have duplicates my @code = ( (int(rand(9)) + 1), (int(rand(9)) + 1), (int(rand(9))...

SSIS “Failed to lock variable” error in File System Task within foreach Loop

variables,foreach,ssis,source,ssis-2012
In SSIS 2012, I have a Foreach Loop and tasks within it to import data from a CSV file and then move the file to an archive folder. In the Foreach Loop Editor, there is a single Variable listed in Variable mappings: User::FilePath. The File System Task within the Foreach...

PHP Foreach same key different value [duplicate]

php,foreach,associative-array
This question already has an answer here: Two arrays in foreach loop 13 answers I've got 2 arrays with the same $key. So arrays are: $users and $new. $users['user_id']=['user_name']; $new['user_id']=['user_color']; How can I foreach them that I could get something like this: foreach (bla bla bla){ echo '<option color="'.$new['user_color'].'"...

How do I modify elements in a Perl array inside a foreach loop?

arrays,perl,csv,foreach
My goal with this piece of code is to sanitize an array of elements (a list of URL's, some with special characters like %) so that I can eventually compare it to another file of URL's and output which ones match. The list of URL's is from a .csv file...

How to map tapped event for a single object in a canvas control in XAML?

c#,xaml,canvas,foreach
I am working on a windows phone RT XAML c# project. I have a canvas filled with several dynamically added balls(ellipse) as ContentControl. I want that, when a ball is tapped, only that particular ball should animate. I have used storyboard animation in the animating function animateBall() and the animation...

How to return multiple results in a php function

php,function,foreach,return
I have the following function that aims to fetch all credits from an artist for a particular song using the ID from the url ($id), and a foreach statement that displays the information on the Web page. At the moment it's displaying the artist names fine, but the IDs aren't...

String.Contains doesnt work as expected with folders returned by Directory.GetDirectories

vb.net,foreach
For some reason, this statement completely bypasses folders which contain said text, what am I doing wrong? For Each fold As String In Directory.GetDirectories("C:\documents") If fold.Contains("pdf") Then I have folders in the c:\documents folder with names such as: pdfone pdfretrieve extrapdf When VS reads through, I see the strings: "c:\documents\pdfone"...

Declaring Variable Outside Foreach Loop in Java

java,for-loop,foreach
Can someone please enlighten me on the following matter: public class Loopy { public static void main(String[] args) { int[] myArray = {7, 6, 5, 4, 3, 2, 1}; int counterOne; for (counterOne = 0; counterOne < 5; counterOne++) { System.out.println(counterOne + " "); } System.out.println(counterOne + " "); int...

PHP foreach loop - need different value from text shown

php,arrays,loops,foreach
I have a simple foreach loop as follows: foreach ($d_38 as $value) { echo " <option value='".$value."'"; if ($results["q".$i]==$value) echo 'selected="selected"'; echo">".$value."</option> "; } I currently have the the information stored in an array called $d_38 this information is placed into the options of the drop down during the foreach...

Remove last row from DataGridView row count

c#,visual-studio,datagridview,foreach,rowcount
I've create a foreach loop in C#. I'm trying to loop trough all the rows except for the last one, which is automatically added. Since the cells contains no values I'm getting a NullException. Important: Setting AllowUsersToAddRows to false is not an option as this function is required. foreach (DataGridViewRow...

How to use dynamic values in Grunt tasks called from inside a forEach?

foreach,gruntjs,grunt-contrib-copy
We are trying to run grunt tasks using grunt.config.set for dynamically concatinated strings. These grunt.configs are set in a forEach loop and change each time before the task is run. This does unfortunately not work, as grunt only uses the last grunt.config.set and runs it multiple times with that very...

I set variables inside foreach loop and they are not echoing outside the loop

php,arrays,foreach
I am setting up an array with $key => $value. I am using this to set up a report from a form submission. I am trying to set a php variable inside the foreach loop and use it outside the loop; however, it isn't working. Any ideas why? $formfields =...

Difficulity with blade foreach

php,twitter-bootstrap,laravel-4,foreach
I am using Laravel 4.2 and I'm stuck in using a blade foreach loop to create a table. The table shows some records and when the user clicks on the details button, a bootstrap modal opens for that record. Unfortunately the opened modal just shows the details for the first...

How can I categorize outputs

php,mysql,loops,if-statement,foreach
I would like to categorize my outputs, because the current result is not the best for me. Mysql table: DATE TITLE CAT 2012-11-23 | Liverpool - Man City | 2 2012-11-23 | Arsenal - Swansea | 2 2012-11-24 | Bolton - Fulham | 3 2012-11-23 | Nagoya - Kashima |...

Foreach error with multi-dimensional from YouTube APIv3

php,multidimensional-array,foreach,youtube
I'm trying to get a Youtube channel's information (channel name, description, thumbnail, etc) with the following PHP: $json_file3 = file_get_contents($query); $jfo3 = json_decode($json_file3,true); foreach($jfo3 as $lv1) { foreach($lv1 as $lv2) { $yt_id = $lv2['id']; $display_name = $lv2['snippet']['title']; $description = nl2br($lv2['snippet']['description']); $yt_thumbnail = $lv2['snippet']['thumbnails']['high']['url']; } } And this is a sample...

PHP array within array

php,arrays,foreach
Can someone explain to me why this isn't working? I'm trying to push an array into another array, but its only coming back with the last item from the $votes array. foreach($json['area'] as $row) { $name = $row['name']; $group = $row['array']['group']; $majority = $row['array']['majority']; $candidates = $row['array']['candidates']; foreach ($candidates as...

C# foreach loop not iterating through item

c#,foreach
Am trying to populate a datagrid with contents of a List, but afterwards the list contains the right amount of items, all with the same data row. For example, when press = 8 there are three different batches returned in SQL, but in C# there is one batch returned three...

Looping through JSON with PHP to get children

php,json,foreach,children
I've been trying all morning to do what would appear to be something quite simple and I'm failing miserably. I have an API request which returns valid JSON data and I need to loop through the various values in PHP to get several nodes into my application. Here is a...

XSLT contains error

xml,xslt,foreach,contains
I apologize for the crude explanation, I'm fairly new to xml and xslt. Thanks for your patience. Here's the challange, I'm trying to build a transformation to csv that creates a new line for each instance of an employee's benefit enrollments. So, if they're enrolled in two plans, a line...

MySQL & PHP: Divide two numbers from two different tables with the same date

php,mysql,loops,foreach
I have this two tables: Table 1: TBL_USD_AUD +----+------------+----------+ | id | date | value | +----+------------+----------+ | 1 | 2015-04-24 | 1.278400 | +----+------------+----------+ | 2 | 2015-04-23 | 1.287200 | +----+------------+----------+ | 3 | 2015-04-22 | 1.288300 | +----+------------+----------+ | 4 | 2015-04-21 | 1.291500 | +----+------------+----------+ |...

AngularJS $http request using forEach inside of Controller

angularjs,http,foreach
http://codepen.io/rcidaleassumpo/pen/eNEjGY?editors=001 That's the link for the code. Below I first used the forEach to combine the nicknames with the base link, so I could get the fullLink to make the call for with the $http. But then when I tried to make the call, and post into a empty array,...

JSTL not printing my passed attribute from servlet. Is scope or not accessing doGet() the issue?

jsp,servlets,foreach,jstl
I'm making a simple blog application. User enters an announcement, its passed to servlet where it is inserted into a database in the POST method via DAO. The GET method creates an arrayList by retrieving all the data via the same DAO and passing it to the view page. Not...

Substitute to `foreach` for individual array values php

php,arrays,foreach
This is the current code setup I have which you see prints out each value in a table cell. foreach($LS::getClan() as $member) { echo "<tr><td><label class='label label-danger'>{$member['rank']} | <span>{$member['level']}</span></label></td><td>{$member['username']}</td><td>{$member['donated']}</td><td>{$member['received']} </td></tr>"; } I don't really know how to explain it but. Uhhhh what I want is to use this for an...

How to get value of button inside the foreach loop using post method

php,html,button,foreach,html-form-post
Objective: Get the value of buttons from $_POST method, inside foreach loop $projects= 'Project1, Project2, Project3'//from mysql database $projectNames = explode(',', $projects); // to separate the project names to display one by one on button. Displaying all the project names on buttons. <?php foreach ($projectNames as $val):?> <form action="projectSelected.php" method="post"...

Editing a sub to use string arrays combined with for each

arrays,excel,vba,excel-vba,foreach
I am trying to set up a bit of code to automate a task I have to do on a weekly report I run. The task is to go into all the 'data' sheets and do several find and replaces so that other parts of the report that refer to...

php in a javascript function not working

javascript,php,html,css,foreach
The folowing code should show me the results of the selected ID : <form id="<?= $blog_id ?>" method="post" action="show.php"> <input type="hidden" name="blog_id" value="<?= $blog_id ?>"> <input type="hidden" name="blog_title" value="<?= $blog_title ?>"> <input type="hidden" name="blog_date" value="<?= $blog_date ?>"> <input type="hidden" name="blog_content" value="<?= $blog_content ?>"> Click <a href="#" onclick="document.getElementById('<?= $blog_id...

Print out something only when value is within specific group during loop in PHP

php,arrays,loops,foreach
I have a big array that is being used throughout the site and changing its structure just for the following task would be a pain. I want to make several select boxes with another array. The output I want to get is like this: /* Example Array: $allAnimals = array("Frogs","Toads","Bats","Elephants","Rats","Seals",...

How to innerHTML a function with array as parameter?

javascript,arrays,loops,foreach,innerhtml
I am learning about looping thorugh arrays - I want to pass the result of an if else statement in the forEach function (inside another function with array as parameter) to HTML using innerHTML (does not have to be innerHTML if you know better methods I do not mind). It...

XNA : 2D Foreach Collision detection issues with a reference of “t” not exiting in current context.

c#,foreach,xna,collision
My problem is that; when doing collision detection using bounding boxes my second player's arrows are not detecting the fact that they are hitting the "pots" on screen. My first player can hit them just fine, when trying to duplicate the player 1's foreach statement for detecting collisions I have...

Can't make update query

codeigniter,foreach
I have in my view 4 selects with the same name - wrappingType[]. They are for 4 different sizes. I tried but I couldn't make update cycle to update data in database. I want when user selects from these 4 selects - these values to be updated in database in...

How to limit table rows per page using PDFsharp?

c#,foreach,pdfsharp
I am using a table to display legend data. The page is in landscape mode. I would like to limit the table rows to 15 per column. 2 columns per page and then a new page is created, and so on. This is the current output. Here is a mockup...

(Java) Efficiency in my Starter Bubble Sort

java,algorithm,optimization,foreach,bubble-sort
I am new to Java and I have a question regarding optimization. How fast is it if I declare before my IF statement a variable that gets the value of x.indexOf(i) + 1 instead of just putting it twice in my code below (which depicts the first call of a...

2 Foreach Loop Inside A Table

php,loops,laravel-4,foreach,blade
I had Users table and group table, when i load a group table, it loads the user which have same group_id as the group table id. it works, but my problem is the foreach was quite a mess. the output looks like this.. however, i want to make the output...

Comparing strings of text files

c#,loops,if-statement,file-io,foreach
I have three text files: file1 file2 and file3 all of which contain emails. file1 is supposed to have all the emails in there, file2 has all emails that are A-M, and file 3 have emails from n-z (This is not important but I figure it would help give a...

Adding table row value into a variable using PHP and MySQL

php,mysql,foreach
This will need some examples: For example this is my MySql dump.sql file: CREATE TABLE IF NOT EXISTS `user` ( `id` int(10) unsigned NOT NULL, `email` varchar(30) NOT NULL, `username` varchar(30) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; INSERT INTO `user` (`id`, `email`, `username`) VALUES (1, [email protected]', 'test1'), (2, [email protected]',...

Loading php foreach values in jQuery bar chart

javascript,php,jquery,foreach,bar-chart
I'm working on jQuery bar chart. Using date range to search free and occupied spaces, entry and exit out of total, Following snapshot will give brief idea of search result; and php forearch is; <?php if(count($occupied) < 1) return; foreach ($occupied as $key=>$value): ?> <tr> <td><?php echo $key; ?></td> <td><?php...

Nested foreach loop in a While loop can make the condition for the while loop go over?

php,loops,foreach,while-loop
Here is a little background on what I am trying to create. I am creating a function called getNextBilling($dateStart,$dateCount = 20) You give it a period length which is the days you want someone to be billed $test->period = '2,5,15'; it takes a starting date which I have assigned on...

Array in Foreach (CodeIgniter)

php,arrays,codeigniter,foreach
I want to use array in foreach loop but failed, here is my code: foreach($this->db->get_where('mytable', array('result' => '1 or 2', 'id' => 'foo'))->result_array() I think 'result' => '1 or 2'piece has a problem but I couldn't find out how can I use array in this kind of foreach. I want...

Change specific keys of multidimensional array in PHP

php,arrays,foreach
I have an two dimensional array called $array. After another question here, I know how to change the whole child array from a two dimensional array like this: Code $keys = array(0, 1); foreach ($keys as $key) { foreach ($array[$key] as $key2 => $value) { $array[$key][$key2] = str_replace($stamm, $stamm2, $value);...

How to echo an str_replace only if array exists in results

php,foreach,echo,str-replace
I'm very amateur when it comes to PHP, so hopefully this makes sense. I have the following foreach loop that fetches all of the "credits" that are linked to a music artist using that artist's id (mixer, producer, arranger, composer, etc). I want to be able to replace the different...

Why/How does a lodash “[iteratee=_.identity] (Function)” in _foreach have a 'mystery' third param?

foreach,underscore.js,lodash
I am getting the hang of lodash.js for the first time today and have discovered that you can access the 'value' 'index' and 'list' within the iterator function. I came across this when using the _.foreach function. For example: _.forEach(oMyArray, function(value, index, list){ ... }) However the API specifies only...

How can one store a binary operator in a variable?

r,foreach,expression
I am pretty confused about the meaning of the %Something% operators. How can one store a binary operator in a variable? Something like... binary_operator = store.binary(%in%) c(3,9,4,1,7) binary_operator c(1:5) # would behave alike "c(3,9,4,1,7) %in% c(1:5)" or something like library(foreach) binary_operator = expression(%do%) # or expression(%dopar%) ... ... foreach (i=1:6)...

How do I insert a value at start and after every 4th element in an array using PHP?

php,arrays,loops,foreach
I have a following array in PHP : $myArray = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o"]; I would like to insert a new element (e.g. 1 after every fourth element in the same array. Also, the array will start with 1....

How to work with Java 8 streams?

java,foreach,java-8,java-stream
I want to know how to work with Java 8 streams and how to use the different kind of available stream operations. For example, I wrote this part of code: ArrayList<State> toBeRemoved = new ArrayList<>(); for (State s : newStates) if (path.contains(s)) // path is a stack of State toBeRemoved.add(s);...

How to see name inside the link after renaming by jQuery?

java,jquery,jsp,foreach
Jsp loop: <c:forEach items="${feedList}" var="feed"> <input type="hidden" readonly="readonly" id="feedId" value="<c:out value="${feed.id}" />" /> <tr> <td class="feed-name" id="<c:out value="${feed.id}" />"><c:out value="${feed.name}" /></td> <td><a href="FeedController?action=delete&id=<c:out value="${feed.id}"/>">Delete</a> </td> <td><a href="FeedItemController?action=feedItemListAsc&id=<c:out...

fill a array with foreach in foreach javascript (angular)

javascript,angularjs,foreach
I have categories. and each category has items. now i return a category list and a item list from the api. now in angular i want to make this into 1 object. I have done the following: if ($scope.categories_norm) { $scope.delivery_items = []; //get categories angular.forEach(data.item_categories.normal_categories, function (v, k) {...

Parallelization doesn't work with the foreach package

r,foreach,parallel-processing,parallel.foreach
Using the foreach package, I was expecting the following line to run in about 10 seconds system.time(foreach (i=1:5, .combine='c') %do% {Sys.sleep(2);i}) user system elapsed 0.053 0.011 10.012 and the following line to run in about 2 seconds system.time(foreach (i=1:5, .combine='c') %dopar% {Sys.sleep(2);i}) user system elapsed 0.069 0.017 10.019 but it...

PHP Mysql PDO query from foreach multiple values stored for output

php,mysql,pdo,foreach,multiple-columns
Today i've been searching on how to store the different values from a query which is injected 4 times with different categories. The result is as i wanted i got the values but when i return them i only get my last query as result. I'm wondering which will be...

Get first object from array using getJSON (JQuery) and for.each

javascript,foreach,getjson
Right now, I am getting multiple values listed because I'm appending the objects from the for each loop. $(document).ready(function(){ $.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=51.522035&lon=-0.105732",function(result){ $.each(result.weather, function(i,item){ $('#testfield').append('<p>' + item.main + '</p>'); }); }); }); I only want to have the 1st object from the JSON output into testfield div, not all of it. I...

Filter Foreach by boolean value in view

c#,asp.net-mvc,view,foreach
I need to be able to filter by a boolean field in my view for my foreach. Here is the code I tried: @foreach (var item in Model.TicketNotes.Reverse() while (item.PublicFlag==false)) If you remove everything after the while it works (minus the filtering out of course....

How to iterate multi dimensional array and calculate sum for each row in php?

php,arrays,loops,foreach,dimensional
i have this array which i retrieved data from my database and put it in an array : $query = "select * from caseunder"; $result=mysql_query($query) or die('Error, insert query failed'); $array[] = array(); $numrows=mysql_num_rows($result); WHILE ($i < $numrows){ $allergies =mysql_result($result, $i, "allergies"); $vege = mysql_result($result,$i, "vege"); $age = mysql_result($result, $i,...

PHP iterating through array returned from a function

php,arrays,loops,foreach
Hi I have a class file which contains a function to retrieve users from a mySQL database. The code is as following : class userdbase { public function fetchUsers() { $db = new mysqli('localhost', 'user', 'pass', 'dbase'); if($db->connect_errno > 0) { die('Unable to connect to database [' . $db->connect_error ....

nested foreach in codeigniter view

php,mysql,codeigniter,activerecord,foreach
I have 4 tables: process, country, process_country and category. Each process belongs to a certain category. A country may have several processes available and a process may be available in several countries. Below is my database structure: category table process table country table process_country -------------- -------------- ------------- --------------- categoryid processid...

How to convert to LINQ Queries

c#,linq,foreach
i want to convert the below for loops into a LINQ query. What i am doing is adding the list of values into a dictionary by using for loop. Now i want them to be executed by using LINQ Queries. Can any one help me in doing that as i...

ERROR: Collection was modified; enumeration operation may not execute. Other solutions are not working for me

c#,sharepoint,foreach
I'm deleteing users in a Sharepoint site and i get this error. Here's my code: foreach (SPUser user in users) { string user_name = user.LoginName; string[]username = user_name.Split('\\'); user_name = username[1].ToString().ToLower(); bool exists= checkIfExists(user_name); if (exists != true) { users.Remove(user.LoginName); } } I've read similar issues but The solutions i...

KnockoutJS foreach on individual element of nested array

javascript,knockout.js,foreach
I am on a project attempting to render search filter facets for a given query, but the rules are such that I cannot simply use nested ko: foreachstatements, as different result sets have different display rules for them. The object I am mapping looks as follows: FacetResults: ko.observableArray([ { Term:...

how to shuffle a php array but keep the index in foreach

php,arrays,foreach,shuffle
i have an array and its data are displayed in a grid using a foreach loop. the index of the foreach is used as part of url for each entry in the grid. $i=0; foreach ($array as $grid) { $name = $grid->name; $address = $grid->address; echo '<li> <a href="javascript:myclick('.$i.');" title="">'...

How to return an array in a foreach loop in PHP [duplicate]

php,arrays,foreach
This question already has an answer here: How to echo an array in PHP? 6 answers I would like to do certain calculation in a function that takes a constant value against different values. To do that I created an array and a variable and also a loop that...

Using 2 foreach for 2 queries - how to use them together

codeigniter,foreach
I have to make statistics - to compare 2 values. I have made 2 queries.Now it looks like that: http://prntscr.com/7ckcq2 These progressive bars repeat many times. It should be only one progressive bar for each question. These statistics show results from a survey. I have to divide average answer of...

trying to get foreach loop to display items with subitems correctly in list items

php,arrays,loops,foreach
I am really trying to get this to work and am close: It loops through the array and does create the submenus (with an error albeit) but: the first menu with submenu items appears correctly but on the second menu that has a submenu items it repeats the first submenu...

Foreach loop inside function with sets of two variables

php,function,loops,foreach
This is a basic example of something I am trying to figure out so I can understand how to apply the same concept to other functions... My question is for example I have a function that will create a series of links that would look something like this: function link($link,...

javascript foreach onclick

javascript,foreach,onclick
<? foreach($words as $word): ?> <li> <button onClick="reply_click()">Show</button> <h4><?php echo $word['Word']['en_words'] ?></h4> </li> <? endforeach; ?> <script> function reply_click() { $("h4").toggle("slow"); } </script> When I click 'button' - shows all, in every foreach, but must show in only one. Where I must used 'this' that this script work? ...

How can i fix this error with this php?

php,function,foreach
I have a problem with my code, when I try to use public function setDatos($aDatosPro){ I have controllerProyectos.php : <?php require "dao/daoProyectos.php"; class NombreProyecto { public function getProyectos() { $aTransfer = new daoProyectos(); $this->setDatos($aTransfer); } public function setDatos($aDatosPro){ $obj = $aDatosPro->resultSelect(); foreach($this->$obj as $sKey=>$oValue){ $list[] = array('Id' => $oValue->getId(),'nombre_proyecto' =>$oValue->getNombreProyecto()/*,'state'...

Usage of the foreach loop in C++

c++,foreach
I've found an example at cpluplus.com. Here it is: #include <iostream> #include <string> #include <regex> int main () { std::string s ("This subject has a submarine as a subsequence"); std::smatch m; std::regex e ("\\b(sub)([^ ]*)"); // Matches words beginning by "sub" std::cout << "Target sequence: " << s << std::endl;...

AngularJS - nested forEach to iterate Json

json,angularjs,loops,foreach
I am trying to print out all the names and books of all of the series. So I use 2 forEach loops but the book info shows up on the console as undefined. Would you please tell me how to fix it? Data: var data = { "records": [ {...

Unwanted typecast in foreach

php,foreach,casting
I am using a function to clean variables for security purposes. However, this function convert each value into a string datatype, which I don't want. So in example, when the input parameter is a integer datatype, the function return a string datatype. Any idea how to return the exact same...

Matched data inside select supposed to selected by default

laravel,if-statement,laravel-4,foreach,blade
I have a database that contains project_development and developer. I want to make an edit form for the project_development that has select with option from developer table. when the data matches, the current option will be selected. It works fine on other select without the foreach loop statement. <select class="form-control"...

Advancing index keys in an array

php,arrays,foreach
I have an array with numerical incrementing keys starting at 0, like 0 1 2 3 4 5 ....etc. I need to assign new keys to the array in the following manner The first three keys keep their index number Every 4th key gets incremented by 4 The two keys...

Send email with body consisting of objects

email,powershell,foreach
I am trying to write a script to search through AD and look for any stale computers and then sends an email to me. However, there are 3 requirements: get the lastlogondate for any pc that is older than 90 days once I get that list, I do a ping...

Equivalent of this jQuery code in pure JS

javascript,jquery,foreach
What would be the equivalent of this piece of code in pure JS (without jQuery)? $.each(data, function(i, item) { if(window.location.href.indexOf(data[i].url) > -1) { slt = data[i].id; if ($(slt).length) { $(slt).html(data[i].html); } } }) I tried this example without a success. var elements = document.querySelectorAll(data); Array.prototype.forEach.call(elements, function(el, i){ alert(el); }); Could...

Error in Array comparison in php

php,arrays,zend-framework,foreach,zend-framework2
Below are the sample arrays I'm Comparing. Table 1 $csvData= ( [0] =&gt; Array ( [Account Number] =&gt; 1.01100156278101E+15 [Posting Date] =&gt; 2014/07/08 [Value Date] =&gt; 2014/07/08 [Description] =&gt; Cash Withdrawal by Cheque-173320--TT1421957901 [Debit Amount] =&gt; 2000 [Credit Amount] =&gt; [Running Balance] =&gt; 388392.62 ) [1] =&gt; Array ( [Account...

How to change jsp loop element with jQuery ajax?

java,jquery,jsp,servlets,foreach
I receive list of feeds from servlets like this: <c:forEach items="${feedList}" var="feed"> <tr> <td><input readonly="readonly" id="feedId" value="<c:out value="${feed.id}" />" /></td> <td id="feed-name"><c:out value="${feed.name}" /></td> <td><a href="FeedController?action=delete&id=<c:out value="${feed.id}"/>">Delete</a> </td> <td><a href="FeedItemController?action=feedItemListAsc&id=<c:out...

sql correct but in php it skips the first result

php,sql,arrays,foreach
I use this: foreach ($result as $row) { $row["testID"], $row["subject"], ... }; to output all the values. The sql works fine but when I go to the page it always shows me all the output without the first element that is in the array. For example if I have 5...

foreach loop with array_combine

php,arrays,foreach
I have changed a for-loop into a foreach loop with array_combine for using two arrays in this foreach. Unfortunately it look like array_combine will just get only unique value, but I need to combine all parts of value-groups like: example: $number = array (1,2,3,4,5,6); //$array = array ('a','a','b','c','d','e'); $array2= array...

Javascript: ForEach loop correct way to access json tag through this method

javascript,php,json,foreach
in order to get only a specific part of the php script i used a foreach with a condition relating to the id so it gave a scoped result. The issue i now have is how to access the information i have... ill show some examples to help illustrate my...

How to call function on every value of String List and change it?

c#,string,foreach
I have a List of Strings and I want to check if they correspond to a specific form. If not i wan't to change that. But I didn't find a nice way to iterate over the elements of the List and change them. I tried to go over list.ForEach(tag =>...

Merge and sum values and put them in an array

javascript,arrays,angularjs,foreach
I'm retrieving values from an external source and apply a foreach loop to the results, with the code below. angular.forEach(data, function(value, key) { if (value.start_date > firstdayOfWeek && value.start_date < lastdayOfWeek) { console.log(value.firstname + ' - ' + value.distance); } else { //do nothing } }); The result is console...

foreach loop with PDO::FETCH_ASSOC, Invalid argument supplied

php,pdo,foreach
I'm quering my database, and want to write a foreach loop, that goes trough my result set, and runs strtotime on the timestamp, in order to use it on my webpage (I want to adjust the array["posted"] value to strtotime(array["posted"]). I am new to php and PDO, and can't figure...

foreach loop in json encode array

php,arrays,json,foreach
I am sending preformatted HTMl with AJAX JSON, JSON have below code, I am trying pull data array from DB and echoing array data, I am not able to put foreach loop in json_encode, because seems my code is wrong at foreach loop, How can i achieve that? echo json_encode(array('returnnews'...

Is it safe to use a C++11 range-based for-loop with an rvalue range-init?

c++,c++11,foreach
Suppose I have a function that returns a std::vector by value: std::vector<int> buildVector(); It would seem natural to iterate over the result using a range-based for: for (int i : buildVector()) { // ... } Question: Is it safe to do so? My reading of the standard (actually, draft n4431)...

Autocreate nested foreach statement

c#,selenium-webdriver,foreach,iterator,auto
I have a simple scenario I am trying to workout which involves auto creating nested foreach statements. What the method is to do is take the int value passed into the method and based on this, it should automatically create nested foreach statements. public static String[] ValuesAdd1 = { "a",...

Acces variable outside foreach Jquery

javascript,jquery,foreach
Im trying to acces my variable but it is giving me an empty array. example: var data = []; $.each(files, function (index, file) { var reader = new FileReader(); reader.onload = handleReaderLoad; reader.readAsDataURL(file); function handleReaderLoad(evt) { data.push({ name: file.name, file: evt.target.result }); } }); console.log(data) At this moment data is...

VBA Macro For-each loop to find string “x” and display differences between sheets for other values

excel,vba,excel-vba,foreach
i have 2 worksheets with 7 columns in the same order, i am trying to match them and show the breaks and matches between the 2 sheets. So I have been able to identify the difference and highlight them blue using VBA, but now i want to show the differences...

how do I create GetEnumerator of my circular list?

c#,foreach,enumerator,circular-list
I have to create my own circular list, I using the generic one. first i create the Node<D> class which represents the data and the next of the element private class Node<D> { public D info; public Node<D> next; public Node() { } public Node(D p) { info = p;...

PHP email not echoing a foreach loop

php,email,foreach
I'm trying to send out a php email that lists all of the products the customer ordered. At first I was just listing the variables for the quantity, products, details, etc. It worked, but only one of the products were being included in the email. So I figured a foreach...

Package `foreach` and void function

r,foreach
I had a quick look at this vignette on the foreach package used to run jobs in parallel. It looks like a pretty powerful package. I think the foreach function always return something. What if I don't want the function to return anything (a void function)? Of course, I could...