Menu
  • HOME
  • TAGS

Create array from another with specific indices

javascript,arrays

You can use .map, like so var data = [ 'h', 'e', 'l', 'l', 'o', ' ' ]; var indices = [ 4, 0, 5, 0, 1, 2, 2 ]; var res = indices.map(function (el) { return data[el]; }); console.log(res); The map() method creates a new array with the results...

Create array/list of many objects(initially unknown amount) by tag

c#,arrays,list,unity3d,gameobject

public List<GameObject> myListofGameObject = new List<GameObject>(); Start(){ myListofGameObject.AddRange(GameObject.FindGameObjectsWithTag("TagName")); myListofGameObject.AddRange(GameObject.FindGameObjectsWithTag("TagName2")); myListofGameObject.AddRange(GameObject.FindGameObjectsWithTag("TagName3")); foreach(GameObject gc in myListofGameObject){ Debug.Log(gc.name); } } Works Perfectly fine for me, Make sure to add the System class for linq generics....

Merging array values into single key and multiple values in php

php,arrays

This line does nothing because it is superseded just a bit later as the same variable is being set: $aExtraFilter2[$extrafilterkey] = []; This line appends to the array regardless of what you have as $value['key'], which is why you get all keys lumped together in the output: array_push($extrafiltervalue, $value['value']); This...

Merge and sum values and put them in an array

javascript,arrays,angularjs,foreach

You cannot store key-value pair in array. Use object to store key-value pair. See comments inline in the code. var obj = {}; // Initialize the object angular.forEach(data, function(value, key) { if (value.start_date > firstdayOfWeek && value.start_date < lastdayOfWeek) { if (obj[value.firstname]) { // If already exists obj[value.firstname] += value.distance;...

How push object onto array of array in Angularjs

javascript,arrays,angularjs

Actually instead of adding properties dynamically you should rethink the structure of the allBooks object you're trying to create. The way I understand it, is that you have a collection of books belonging together, which in their turn belong to another collection. In other words you have an array of...

is there an equivalent of the ruby any method in javascript?

javascript,arrays,ruby,iteration

You are looking for the Array.prototype.some method: var match = arr.some(function(w) { return w.indexOf('z') > -1; }); ...

do calculation inside JSONArray in Java

java,arrays,json

Here's what I would do. Replace <JSON STRING HERE> with the JSON String you were going to parse: ArrayList<ArrayList<Integer>> resultList = new ArrayList<ArrayList<Integer>>(); JSONArray arr = new JSONArray(<JSON STRING HERE>); for(int i = 0; i < arr.length(); i ++) { JSONObject obj = arr.getJSONObject(i); JSONArray valueArray = obj.getJSONArray("values"); ArrayList<Integer> dataList...

Universal function for getting all unique pairs, trebles etc from an array in javascript

javascript,jquery,arrays,performance,underscore.js

Basically combine() takes an array with the values to combine and a size of the wanted combination results sets. The inner function c() takes an array of previously made combinations and a start value as index of the original array for combination. The return is an array with all made...

Notice: Array to string conversion in “path of php file” on line 64

php,mysql,arrays,oracle

Curly brackets are your friend when inserting variables into double quoted strings: $main_query=oci_parse($connection,"INSERT INTO ROTTAN(NAME,ROLLNO) VALUES('{$array[$rs][0]}','{$array[$rs][1]}')"); ...

PHP get one row from an array based on a variables value

php,arrays,mysqli

In your loop you could just do something like: if ($id == $row['id']) { $info[] = $row; } However it would make more sense to me to just update your query. SELECT cols FROM t1 WHERE id = :id Using $id as a parameter....

Javascript sort array of objects in reverse chronological order

javascript,arrays,sorting

As PM 77-1 suggests, consider using the built–in Array.prototype.sort with Date objects. Presumably you want to sort them on one of start or end: jobs.sort(function(a, b) { return new Date(a.ys, a.ms-1) - new Date(b.ys, b.ms-1); }) ...

Read JSON double dimensional array in Java

java,android,arrays,json

You're trying to parse a JSON array into a JSON object. Of course it's going to give you errors. Try this instead: JSONArray agent = jsonObject.getJsonArray("agent"); // To get the actual values, you can do this: for(int i = 0; i < agent.size(); i++) { JSONObject object = agent.get(i); String...

Get enemy's possible moves in chess to a 2D array - Python

python,arrays,chess

Iterate over the pieces on the board. For each piece, narrow down the destination squares according to the move rules for that piece: King can move to the adjacent 8 squares or two squares to each side Pawns can move one or two squares ahead or one diagonally ahead. etc....

php for loop of an array

php,html,arrays,for-loop

Assuming you have properly named the input values, e.g.: <input name="topay[0]" type="checkbox"> <input name="loadnum[0]" value="5"> <input name="unit[0]" value="101"> <input name="driver[0]" value="joe"> <input name="topay[1]" type="checkbox"> <input name="loadnum[1]" value="6"> <input name="unit[1]" value="103"> <input name="driver[1]" value="mike"> Take note of the topay[0] and topay[1] notation that I'm using, as opposed to your form input...

Selecting a 'property value' from an array based on another 'property value' in javascript

javascript,arrays

basically you're looking at something like this var f = function(id){ var match = nodes.filter(function(d){ return d.ID === id; }) return match && match.length && {x: match[0].x, y:match[0].y} || {x: undefined, y: undefined}; }; then f('101') outputs {x: 100, y:200} and if cannot find a match then it will output...

How to check if data already exists then randomly generate new data from an Array

php,mysql,arrays,mysqli

In my personal opinion, NEVER try to get data from an array within quotes! Always do it outside of quotes; especially in multi-denominational arrays. '$input[$rand_keys[$i]]' should be rewritten as '".$input[$rand_keys[$i]]."' OR '{$input[$rand_keys[$i]]}'. In my opinion it is better to do it outside of quotes instead of using { }. ...

Find Maximum of 3D np.array along Axis = 0

python,arrays,numpy

you can do this with numpy.argmax and numpy.indices. import numpy as np X = np.array([[[10, 1],[ 2,10],[-5, 3]], [[-1,10],[ 0, 2],[ 3,10]], [[ 0, 3],[10, 3],[ 1, 2]], [[ 0, 2],[ 0, 0],[10, 0]]]) Y = np.array([[[11, 2],[ 3,11],[-4, 100]], [[ 0,11],[ 100, 3],[ 4,11]], [[ 1, 4],[11, 100],[ 2,...

Segmentation Fault if I don't say int i=0

c,arrays,segmentation-fault,initialization,int

In your code, int i is an automatic local variable. If not initialized explicitly, the value held by that variable in indeterministic. So, without explicit initialization, using (reading the value of ) i in any form, like array[i] invokes undefined behaviour, the side-effect being a segmentation fault. Isn't it automatically...

Trying to solve symmetric difference using Javascript

javascript,arrays,symmetric-difference

Here's a version that uses the Set object to make for faster lookup. Here's the basic logic: It puts each array passed as an argument into a separate Set object (to faciliate fast lookup). Then, it iterates each passed in array and compares it to the other Set objects (the...

Setting array key value pair JavaScript

javascript,arrays,key,value,pair

Trim your key because cookie strings look like this: "__utma=250730393.1032915092.1427933260.1430325220.1430325220.1; __utmc=250730393; __utmz=250730393.1430325220.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); clicks=22; _gat=1; _ga=GA1.2.1032915092.1427933260" so when you split on ; there will be an extra space before some of the key names. function getcookie(cookiename){ var mycookies = []; // The cookie jar var temp = document.cookie.split(";"); var key =...

Display only values containing specific word in array

php,arrays,json,string,if-statement

You can use substr_count() <?php foreach($soeg_decoded as $key => $val){ $value = $val["Value"]; $seotitle = $val["SEOTitle"]; $text = $val["Text"]; if(substr_count($value, $searchText) || substr_count($seotitle, $searchText) || substr_count($text, $searchText)){ echo '<tr><td>' . $value . '</td><td>' . $seotitle . '</td><td>' . $text . '</td></tr>'; } } ?> Read more at: http://php.net/manual/en/function.substr-count.php ...

C++ & Qt: Random string from an array area

c++,arrays,string,qt,random

You should use the random header. #include <random> std::default_random_engine generator; std::uniform_int_distribution dist(0, 5); int StringIndex = dist(generator); std::string ChosenString = characters[StringIndex]; The above will generate a random index into your array. If you want to limit the range, change the constructor of dist, for example (dist(0,2) would only allow for...

Blank screen on GridView

android,arrays,gridview

I executed ur code. Just add numberView.setTextColor(Color.BLACK); and it will work! :)...

javascript better way to “reset” an array

javascript,arrays

I think you can do, but it will change the array referenced by arrayA -- populate arrayA and arrayCache using for loop -- shuffle arrayA /* empty arrayA */ arrayA = []; - /* THIS IS THE IMPORTANT PART, reset the array (load values from arrayCache into arrayA) */ arrayA...

Explode Array and store in db

php,arrays

You do not need to use explode. i think this is what you want: $q = "INSERT INTO ".TBL_ARE_ENTRY." VALUES(null,''$array[0][0]','$array[0][1]',''$array[0][2]')"; ...

Ruby: How to copy the multidimensional array in new array?

ruby-on-rails,arrays,ruby,multidimensional-array

dup does not create a deep copy, it copies only the outermost object. From that docs: Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. If you are not sure how deep your object...

isset - else inside an array used to create a form

php,arrays

Ternary condition act as a IF...ELSE condition $this->form[] = array( 'surname' => (isset($vars['sur_name']) ? $vars['sur_name'] : $current_user->user_lastname) ); is the same thing as if (isset($vars['sur_name']){ $this->form[] = array('surname' => $vars['sur_name']); } else { $this->form[] = array('surname' => $current_user->user_lastname); } read about ternary operator here...

Split an array into slices, with groupings

arrays,ruby,enumerable

Yes, this bookkeeping with i is usually a sign there should be something better. I came up with: ar =[ { name: "foo1", location: "new york" }, { name: "foo2", location: "new york" }, { name: "foo3", location: "new york" }, { name: "bar1", location: "new york" }, { name:...

Having two arrays in variable php

php,mysql,arrays,variables,multidimensional-array

The explode function is being used correctly, so your problem is further up. Either $data[$i] = mysql_result($result,$i,"data"); isn't returning the expected string "2015-06-04" from the database OR your function $data[$i] = data_eng_to_it_($data[$i]); isn't returning the expected string "04 June 2015" So test further up by echo / var_dump after both...

Return index of word in string

arrays,vb.net,vbscript

Looking at your desired output it seems you want to get the index of word in your string. You can do this by splitting the string to array and then finding the item in an array using method Array.FindIndex: Dim animals = "cat, dog, bird" ' Split string to array...

array and function php

php,arrays

$x and $y are only defined within the scope of the function. The code outside of the function does not know what $x or $y are and therefore will not print them. Simply declare them outside of the function as well, like so: <?php function sum($x, $y) { $z =...

Filter array of objects with another array of objects

javascript,jquery,arrays,object,filter

var filtered = []; for(var arr in myArray){ for(var filter in myFilter){ if(myArray[arr].userid == myFilter[filter].userid && myArray[arr].projectid == myFilter[filter].projectid){ filtered.push(myArray[arr].userid); } } } console.log(filtered); ...

Comparing arrays with numbers in vb.net

arrays,vb.net

There are a few basic ways of checking for a value in an integer array. The first is to manually search by looping through each value in the array, which may be what you want if you need to do complicated comparisons. Second is the .Contains() method. It is simpler...

jquery get elements by class name

html,arrays,parsing,getelementsbyclassname

You can do it like this way: $('.x:eq(0)').text('changed text'); or: $('.x').eq(1).text('bbb'); both works well sorry for my before answer.....

Infinite loop with fread

c,arrays,loops,malloc,fread

If you're "trying to allocate an array 64 bytes in size", you may consider uint8_t Buffer[64]; instead of uint8_t *Buffer[64]; (the latter is an array of 64 pointers to byte) After doing this, you will have no need in malloc as your structure with a 64 bytes array inside is...

Initializing a multidimensional array

c++,arrays,multidimensional-array,initialization

If you want to copy the values of temp array , instead of "=", you should use memory copy memcpy( test[i], temp, sizeof(temp[192])); ...

Javascript program keeps outputting wrong index of array

javascript,arrays,alert

The problem can be reduced to this: var Foo = { courses: [] }; var x = Object.create(Foo); var y = Object.create(Foo); x.courses.push(123); alert(y.courses[0]); // "123" The reason for this behaviour is that both objects inherit the same prototype and any changes made to .courses will apply to both objects....

PHP Merge (Add) Two Arrays by Same Key

php,arrays,array-merge

As mentioned in the comments, looping through the array will do the trick. $a = array('a' => 2, 'b' => 5, 'c' => 8); $b = array('a' => 3, 'b' => 7, 'c' => 10); $c = array(); foreach($a as $index => $item) { if(isset($b[$index])) { $new_value = $a[$index] +...

textbox search through array with keys and display closest results

javascript,jquery,arrays

I'm not sure if this what you looking for you can use it in local by providing your array or ajax https://github.com/devbridge/jQuery-Autocomplete Ajax lookup: $('#autocomplete').autocomplete({ serviceUrl: '/autocomplete/countries', onSelect: function (suggestion) { alert('You selected: ' + suggestion.value + ', ' + suggestion.data); } }); Local lookup (no ajax): var countries =...

Perl: Using Text::CSV to print AoH

arrays,perl,csv

Pretty fundamentally - CSV is an array based data structure - it's a vaguely enhanced version of join. But the thing you need for this job is print_hr from Text::CSV. First you need to set your header order: $csv->column_names (@names); # Set column names for getline_hr () Then you can...

reform of multidimentional array in php

php,arrays

I guess whats your looking for is something like this $new_arr = array(); foreach($arr as $emp => $emp_arr){ foreach($arr[$emp] as $projectArray => $projectArray_arr){ foreach($arr[$emp][$projectArray] as $date => $value3){ @$new_arr[$emp][$projectArray]['estimated_time'] += $arr[$emp][$projectArray][$date]['estimated_time']; @$new_arr[$emp][$projectArray]['cost'] += $arr[$emp][$projectArray][$date]['cost']; } } } ...

Unable to convert between 1d and 2d array values

java,arrays,matrix,2d

All arrays start by 0, try this: public static void main(String[] args) { int testSize = 4; Test test = new Test(testSize); for (int i = 0; i < testSize; i++) { for (int j = 0; j < testSize; j++) { int index = test.toIndex(i, j); int coordinates[] =...

Sort array by keys in custom order

php,arrays,sorting

You could use the following comparison function: function cmp($a, $b) { $order = Array( 'LOW' => 0, 'MEDIUM' => 1, 'HIGH' => 2 ); return $order[$a] - $order[$b]; } Example of this code is here....

Javascript: Labeling array results

javascript,arrays

Change you show function to this function show() { var content="<b>Your Plans For the Day:</b><br>"; for(var i = 0; i < Name.length; i++) { content += "Name " + Name[i]+"<br>"; } for(var i = 0; i < Date.length; i++) { content += "Date" + Date[i]+"<br>"; } for(var i = 0;...

Zipping two arrays together with index in Scala?

arrays,scala,zip

Simply do: array1.zip(array2).zipWithIndex.map { case ((a, b), i) => (a, b, i) } ...

export mysql query array using fputcsv

php,mysql,arrays,csv,fputcsv

Corresponding to official manual for mysqli_fetch_array: mysqli_fetch_array — Fetch a result row as an associative, a numeric array, or both You coded MYSQLI_ASSOC flag, so yo get associative array for one row of data: By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc() See examples of...

Reorder an array around an index

javascript,arrays,underscore.js,lodash

How about one line: var array = array.slice(2, array.length).concat(array.slice(0, 2)); DEMO...

char* string substract function throws exception

c++,arrays,string,char

The first obvious mistake you're doing here is this: char* temp = new char[255]; temp = this->c_str(); You allocate memory then you're copying the value of a pointer. So first you're getting a memory leak and second depending on your implementation of c_str() you are copying the address of something...

accessing range of values in arduino array

arrays,arduino

Arrays in C++ don't allow this syntax. What you should do is something like this: char[2] id; if( sx1272.packet_received.length > 5 ) { id[0] = sx1272.packet_received.data[4]; id[1] = sx1272.packet_received.data[5]; } ...

Remove Strings with same characters in a String Array

java,arrays,string

TreeSet allows us to give a comparator. See whether this helps. package empty; import java.util.Arrays; import java.util.Comparator; import java.util.Set; import java.util.TreeSet; public class RemoveDuplicateStrings { public static void main(String[] args) { String[] name1 = {"amy", "jose", "jeremy", "alice", "patrick"}; String[] name2 = {"alan", "may", "jeremy", "helen", "alexi"}; String[] name3 =...

Array breaking in Pebble C

c,arrays,pebble-watch,cloudpebble

The problem is this line static char *die_label = "D"; That points die_label to a region of memory that a) should not be written to, and b) only has space for two characters, the D and the \0 terminator. So the strcat is writing into memory that it shouldn't be....

Given an array/object of datetimes, how can I return an array/object of the times sorted by hour and times sorted by days of the week

php,arrays,sorting,datetime,laravel

You can use Laravel's collection groupBy method to group your records for your needs. $records = YourModel::all(); $byHour = $records->groupBy(function($record) { return $record->your_date_field->hour; }); $byDay = $records->groupBy(function($record) { return $record->your_date_field->dayOfWeek; }); Remember that this code to work, you have to define your date field in the $dates Model array, in...

How do I store the value of the max integer in an array before repeating loop?

arrays,max

max=0; for (count=0;count<SIZE;count++){ if (myArray[count]>max){ max = myArray[count]; } } You need change all <= SIZE to < SIZE ...

How to add new items to an array in MongoDB

arrays,node.js,mongodb

$set is not an array update operation. The $set operator replaces the value of a field with the specified value. You just want to use $push by itself, as in .update({_id: id}, {$push: {name: item}}) You can't interpolate object property names in raw object declarations, so if you want to...

How to get range of 10 items from the arraylist in java? [on hold]

java,arrays,arraylist,pagination

You can use ArrayList.subList() giving the parameters as the start index and end index. Start index - inclusive. End index - exclusive. Exmaple - ArrayList a = new ArrayList(); a.add(1); a.add(2); a.add(3); a.add(4); a.add(5); a.add(6); System.out.println(a.subList(0,4)); It prints out - [1, 2, 3, 4] The above would print out first...

creating a 3d array in python does not create array correctly

python,arrays,3d

You should use labels.append instead of numpy.append Example code - labels = [] for line in lines: lab = [h/100, maxf, title] labels.append(lab) Also this would create the labels list as - [[1,34,u'te],[2,44,u've],[4,43,u'ht]] [1,34,u'te],[2,44,u've],[4,43,u'ht] is not possible in python, these are either three different lists, or they are enclosed by...

SCALA: change the separator in Array

arrays,string,scala,delimiter

Your question is unclear, but I'll take a shot. To go from: val x = Array("a","x,y","b") to "a:x,y:b" You can use mkString: x.mkString(":") ...

Substring of a file

javascript,arrays,substring

To get your desired output, this will do the trick: var file = "a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d"; var array = file.split(", ") // Break up the original string on `", "` .map(function(element, index){ var temp = element.split('|'); return [temp[0], temp[1], index + 1]; }); console.log(array); alert(JSON.stringify(array)); The split converts...

Getting front value from array/json

php,arrays,json

You can use $array["image_intro"],this will give you the value of image_intro. check out the manual

Java comparing 2D array to digit is giving exceptions

java,arrays,multidimensional-array

It is because you are trying to access to the row 8 and you only have the maximum of position 7. Remember that the index of rows and columns starts in the position 0 and ends in the length-1. Also, you have to remember that the first position of the...

most efficient way to create javascript array out of various php arrays

javascript,php,jquery,arrays

John, Try this: var dataSet = []; for (i = 0; i < mfrPartNumber.length; i++ ) { data = [dateReceived[i],name[i],color[i]]; dataSet.push(data); } This will build an array out of each instance of [i], and keep growing as your user keeps pushing the button....

jQuery create a real-time array from multiple inputs with the same class

jquery,html,arrays,class

Your current code is changing emailObj from an object to a string on each iteration of the loop, instead of amending a property of the object itself. Also note that you can use the . style selector to match elements by their class. To achieve what you require, you can...

Fail to create array with query values

php,mysql,arrays,pdo

Your variable assignments are all wrong. They should be: $range = $_COOKIE["range"]; $longitude = $_COOKIE["longitude"]; $latitude = $_COOKIE["latitude"]; When you try to use a non-numeric string as a number in an arithmetic expression, it's treated as 0. So the result of your code was effectively: $le = 0 * $onemile;...

Javascript function to validate contents of an array

javascript,arrays

You can use a simple array based test like var validCodes = ['IT00', 'O144', '6A1L', '4243', 'O3D5', '44SG', 'CE64', '54FS', '4422']; function validItems(items) { for (var i = 0; i < items.length; i++) { if (validCodes.indexOf(items[i]) == -1) { return items[i]; } } return ''; } var items = ["IT00",...

Filling PHP array with “for” loop

php,arrays,for-loop,population

Try this Code : $maxPages = 20; $targets = array(); for ($i = 0; $i <= $maxPages; $i++) { $url = 'http://127.0.0.1/?page='.$i; $targets[$url] = array( CURLOPT_TIMEOUT => 10 ); } echo "<pre>"; print_r($targets); ...

AngularFire pushing to array doesn't work

javascript,arrays,angularjs,firebase,angularfire

You only need to call $save on $firebaseObject instances. In fact the call to $save might well break things, since it triggers a potential race condition between the push and the $save. Update This will work: groupControllers.controller('MemberGroupController', ['$scope', '$firebaseArray', '$routeParams', '$location', '$routeParams', function($scope, $firebaseArray, $routeParams, $location, $routeParams) { $scope.groups =...

Array JLabel ActionListener multiple JPanels

java,arrays,swing

You cannot directly add an ActionListener to a JLabel - it doesn't have that functionality. Instead, you should create a MouseAdapter, override the mouseClicked method, and use JLabel.addMouseListener to add it to your JLabels. The best way to get it to, as you say, "display a panel and the other...

Opening multiple files in perl array

arrays,perl

You just need to enclose the code that handles a single file in a loop that iterates over all of the log files You should also reconsider the amount of comments that you use. It is far better to write your code and choose identifiers so that the behaviour is...

Passing an array through a constructor

java,arrays,constructor

The values are going into the array but you're doing nothing with them. Probably you want/need to display the values, so use System.out.println public static void main(String[] args) { SArray tester = new SArray(new int[] {23, 17, 5, 90, 12, 44, 38, 84, 77, 3, 66, 55, 1, 19, 37,...

Javascript Sorting Array of Objects [duplicate]

javascript,arrays,sorting,object

You use a custom callback with the array method .sort(). Arr.sort(function(a, b) { return a.age - b.age; }); MDN reference page on .sort(). And, here's a working snippet: var Obj1 = {firstName: "John", lastName: "Doe", age: 46}; var Obj2 = {firstName: "Paul", lastName: "Smith", age: 22}; var Obj3 = {firstName:...

pointer to pointer dynamic array in C++

c++,arrays,pointers

The valid range of indices of an array with N elements is [0, N-1]. Thus instead of for example this loop for (int i=1; i <= n; i++) ^^^^ ^^^^^^ you have to write for ( int i = 0; i < n; i++ ) As you used operator new...

How do I print more than one value per key in Tcl?

arrays,tcl

You can't do it with arrays or dictionaries; both are mappings from keys to values. Instead, you need to use foreach with a key-value pair system directly: set pairs { set1 table set2 chair set1 chair } foreach {key value} $pairs { puts "$key is $value" } This does actually...

PHP Array combine using one column value

php,arrays

You can traverse those arrays and make changes like below : foreach ($array1 as &$a1val) { $value = 0; foreach ($array2 as $a2val) { if($a1val->uuid == $a2val->uuid) { $value = $a2val->value; break; } } $a1val->value = $value; } P.S. : & is used to update $array1 by reference. ...

Multiply arrays by arrays in JAVA

java,arrays,xml,permutation

Something like this? import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MatrixCross { public static void cross(String[]... matrix){ cross(0,matrix, Collections.EMPTY_LIST); } private static void cross(int index,String[][] matrix, List<String> result){ if (index >= matrix.length){ System.out.println("<test>"); int i = 1; for (String str : result) { System.out.println(" <test_"+i+">"+str+"</test_"+i+">"); i++; } System.out.println("</test>"); }...

Android Array from text file(s)

android,arrays

You can use Filereader. You have to create 2 different Filereader. And then you can get the texts from textfiles and add them to Arrays. If you learn enough about filereader you wil easily make what you want. It is really easy to use filereader.

php array returns undefined but print_r shows otherwise [duplicate]

php,arrays,json,undefined

The array you're looping looks like this: Array ( [0] => Array ( [mstatus] => 1 [mhearingnum] => first [mminutes] => adakjaflafjlarjkelfkalfkd;la ) [1] => Array ( [mhearingnum] => second [mminutes] => ) [2] => Array ( [mhearingnum] => third [mminutes] => ) ) Only the sub array at the...

jQuery - Value in Function

jquery,arrays,function

You need to use brackets notation to access property by variable: function myFunc( array, fieldToCompare, valueToCompare ) { if( array[fieldToCompare] == "Thiago" ) alert(true); } And wrap name in quotes: myFunc( myArray, 'name', "Thiago" ); ...

Javascript : How do I call the array index of the string?

javascript,arrays

You have to split() the string to get an array of indexes instead of a string of indexes : var indexes = '0,2'.split(','); //use the ',' char to split the string Now, you have to pick fruits values corresponding to each index in the new indexes array create just before....

Building an array of search parameters

php,arrays

From the given array it will produce 54 possible combinations as you described. Also you need to make sure you have array in $allOptions['BrowseNode'] indexed as each value of $allOptions['SearchIndex']. Otherwise it will produce error. Cartesian function from here. $allOptions = [ "SearchIndex" => ["SportingGoods", "Tools"], "MinPercentageOff" => ["50", "60",...

Twitter Typehead, listing object arrays

javascript,jquery,arrays,twitter

I have modified your code, Instead of passing a object, passing an array to 'local' option should do the work. Since your source is an array of object, it is better to specify which property value to show by adding 'display' option. var phones = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('phone'), queryTokenizer:...

Select word between two words

javascript,arrays,jquery-selectors

Here's a quick split and reduce: var arr = str.split("By ").reduce(function(acc, curr) { curr && acc.push(curr.split(" ")[0]); return acc; }, []); Result: ["Greili", "ToneBob", "hela222", "NovaSplitz"] Demo: JSFiddle...

How to pivot array into another array in Ruby

arrays,ruby,csv

Here is a way using an intermediate hash-of-hash The h ends up looking like this {"Alaska"=>{"Rain"=>"3", "Snow"=>"4"}, "Alabama"=>{"Snow"=>"2", "Hail"=>"1"}} myArray = [["Alaska","Rain","3"],["Alaska","Snow","4"],["Alabama","Snow","2"],["Alabama","Hail","1"]] myFields = ["Snow","Rain","Hail"] h = Hash.new{|h, k| h[k] = {}} myArray.each{|i, j, k| h[i][j] = k } p [["State"] + myFields] + h.map{|k, v| [k] + v.values_at(*myFields)} output...

how to modify an array value with given index?

arrays,linux,bash

You don't need the quotes. Just use ${i}, or even $i: pomme[${i}]="" Or pomme[$i]="" ...

How to group several JSON objects which contains array with same id together

jquery,arrays,json

var result = [ { "data": [{ "id": 1, "name": "aaa" }] }, { "data": [{ "id": 2, "name": "bbb" }] }, { "data": [{ "id": 1, "name": "cccc" }] }, { "data": [{ "id": 3, "name": "ddd" }] }, { "data": [{ "id": 2, "name": "eee" }] }, {...

How can i return twice same name of filed for different tables in PHP?

php,arrays

I am not sure where $p gets set to anything or why you are in a foreach loop that uses $sql as the array but, using your logic and assuming its correct change your php like this <?php foreach ( $sql as $x => $y ) : ?> <tr style="text-align:...

Get elements containing text from array

javascript,jquery,html,arrays,contains

You can use :contains selector. I think you meant either one of those values, in that case var arr = ['bat', 'ball']; var selectors = arr.map(function(val) { return ':contains(' + val + ')' }); var $lis = $('ul li').filter(selectors.join()); $lis.css('color', 'red') <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul> <li>cricket bat</li> <li>tennis ball</li> <li>golf ball</li>...

Storing result from FOR loop as one array (array only saves each results seperately)

javascript,jquery,arrays,ajax

Here is my Solution var id = "1#2#3#4#5#"; var chkdId = id.slice(0, -1); console.log(chkdId); var arr = chkdId.split('#'); var checkedId = ''; var chkdLen = arr.length; // here is the array var arrayWithResults = []; for (var i = 0; i < chkdLen; i++) { checkedId = arr[i]; var checkedId...

How to innerHTML a function with array as parameter?

javascript,arrays,loops,foreach,innerhtml

Just take a variable for the occurrence of even or odd numbers. var myArray = function (nums) { var average = 0; var totalSum = 0; var hasEven = false; // flag if at least one value is even => true, otherwise false nums.forEach(function (value) { totalSum = totalSum +...

Translating a character array into a integer string in C++

c++,arrays,string

If you want a sequence of int, then use a vector<int>. Using the key_char string, the values of the chars in it will serve as the initial value of the ints. std::vector<int> key_num(key_char.begin(), key_char.end()); Then, iterate over each character of key_num and convert it to the equivalent int value for...

Best way to save traffic in iOS Parse App

ios,arrays,swift,parse.com,traffic

You can create Parse class for your feed objects. After that create an array column to store objectIds of users who added your feed item to favorit. When you want to find all the objects specific user bookmarked do something like PFQuery *query = [PFQuery queryWithClassName:@"feedObjects"]; [query whereKey:@"favoritesArray" equalTo:@"YOUR USER...