PHP & JS numeric and assoc arrays index trouble
This problem is probably trivial for 99% of you. So far I always tried to avoid situation like this, but now I don't have any choice.
For PHP:
$array = array();
$array[5] = 'Element';
$array['s_5'] = 'Alternative Element';
$array[7] = 'Element2';
$array['s_7 '] = 'Alternative Element2';
For JS
var array = new Array();
array[5] = 'Element';
array['s_5'] = 'Alternative Element';
array[7] = 'Element2';
array['s_7 '] = 'Alternative Element2';
And now I need to get to secondth element of array. How to do it? Of course I could create another table containing array keys for each element, or use foreach/while and do some action on specific element. Also I can get last array element in 开发者_StackOverflowPHP using end(), but is there any other, faster way to get specific element from random array (implying I don't know keys and length of array)?
Thanks for helping me.
You might want to use a 2 dimensional array instead:
$matrix = array();
$matrix['elements'] = array();
$matrix['alt_elements'] = array();
$matrix['elements'][5] = 'Element';
$matrix['alt_elements'][5] = 'Alternative Element';
etcetera...
Avoid using associative arrays in JS. Use arrays only when the keys are numeric. Otherwise, use objects.
var matrix = {};
matrix.elements = [];
matrix.altElements = [];
matrix.elements[5] = 'Element';
matrix.altElements[5] = 'Alternative Element';
Associative arrays (php) or objects (js) are not meant to be accesed by numeric index. This includes accessing the n-th element.
If you really have to do it there's no good way except iterating over the array using foreach($arr as $key => $val)
in php or for(var key in obj)
in js and counting the elements manually.
However, if your arrays resemble a matrix, you might want to create two matrices or make the innermost element an array so you have plain numeric arrays for the actual matrix and just for the data inside something else.
精彩评论