I have an array im trying to loop through to create a new type of array specific to my current page.
My array looks like this:
//$_SESSION['data'] =
Array (
[0] => 1
[1] => 0
[2] => Tom
[8] => 1
[4] => 1
[5] => Array (
[7] => Array (
[0] => Andrew
[1] => 1
[2] => 1
[4] => 0
[5] => avatar.jpg
[6] => 1
)
)
[6] => Array ( [0] => 1
[1] => 2
)
)
So in my JS file i have this:
var stats = <? echo json_encode($_SESSION['data'][5]); ?> ; //this is the array
my_data = new Array();
for(var key in stats){
if(key in my_data){} else { //prevent double entry
my_data[key] = new Array();
my_data[key][0] = stats[key][6];
my_data[key][1] = stats[key][5];
my_data[key][2] = stats[key][2];
my_data[key][3] = stats[key][0];
}
}
console.log(my_data);
Now in console.log i get this :
[undefined × 7, Array[4]
0: "1"
1: "avatar.jpg"
2: "1"
3: "Andrew"
length: 4
__proto__: Array[0]
]
I’m wondering why it is saying undefined x7?
Why not use JSON??
YOu can now iterate normally.
UPDATE
Yes, you will get ‘x7 undefined’. This is because you are directly setting the 8th entry in the js array. (key == 7 in the iteration of for-loop) First 7 entries are essentially undefined.
If you want to use the first few indices, use
array.push(..)or manually set the last index usingarray[array.length] = new_object;