I'm currently fetching an array with .each:
$.each(messages, function(key,message){ doStuff(); });
But the key is the index of the array and not the associative key.
How can I get it easily?
Answer: Use the PHP array_keys() function You can use the PHP array_keys() function to get all the keys out of an associative array.
An associative array is an array with string keys rather than numeric keys. Associative arrays are dynamic objects that the user redefines as needed. When you assign values to keys in a variable of type Array, the array is transformed into an object, and it loses the attributes and methods of Array.
use array_keys() to get an array of all the unique keys. Note that an array with named keys like your $arr can also be accessed with numeric indexes, like $arr[0] .
The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.
JavaScript doesn't have "associative arrays". It has arrays:
[1, 2, 3, 4, 5]
And objects:
{a: 1, b: 2, c: 3, d: 4, e: 5}
Array's don't have "keys". They have indices, which are counted starting at 0.
Arrays are accessed using []
, and objects can be accessed using []
or .
.
Example:
var array = [1,2,3];
array[1] = 4;
console.log(array); // [1,4,3]
var obj = {};
obj.test = 16;
obj['123'] = 24;
console.log(obj); // {test: 16, 123: 24}
If you try to access an array using a string as a key instead of an int, that may cause problems. You would be setting a property of the array and not a value.
var array = [1,2,3];
array['test'] = 4; // This doesn't set a value in the array
console.log(array); // [1,2,3]
console.log(array.test); // 4
jQuery's $.each
works with both of these. In the callback for $.each
, the first parameter, key
, is either the object's key, or the array's index.
$.each([1, 2, 3, 4, 5], function(key, value){
console.log(key); // Logs 0 1 2 3 4
});
$.each({a: 1, b: 2, c: 3, d: 4, e: 5}, function(key, value){
console.log(key); // Logs 'a' 'b' 'c' 'd' 'e'
});
var data = {
val1 : 'text1',
val2 : 'text2',
val3 : 'text3'
};
$.each(data, function(key, value) {
alert( "The key is '" + key + "' and the value is '" + value + "'" );
});
See the Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With