Bwizard
Bwizard

Reputation: 1023

Set the JSON Key to increment inside a loop

I have an array within my json output from a php file which uses the key 0,1,2 etc

I am having trouble accessing the key through javascript. I'm not sure what the issue is with using numbers. All the other data has a text value key which I can access using data.arrayname.key. To get around the issue I would like to set the key to a string with a number at the end so I can reference it back in javascript easily.

The array is pushed to each time in a loop. Within the loop I have tried

 $NoOfTips++;
 $jsonKey = 'Tip' + $NoOfTips;
 $TBarray[$jsonKey]=$line;
 array_push($TBarray);

In theory each time the loop goes round NoOfTips should increase by 1 which would also change the key to Tip1,Tip2,etc but obviously something is amiss. Could somebody please explain how why the Key is not being set correctly.

Thanks

Upvotes: 1

Views: 680

Answers (1)

dave
dave

Reputation: 64687

To answer the real issue - to access a numeric index in javascript, you can't use dot notation, you would instead use brackets:

var data = { tips: { 1: "one", 2: "two" }, other: [1, { test: "tested" }] }
console.log(data.tips[1], data.other[0], data.other[1].test)
// output: one 1 tested

For the php side, when you do array_push, you have to specify the array you are pushing to, as well as what you are pushing:

array_push($TBarray, $line)

for example. I'm not sure what you are going for there, though.

Upvotes: 2

Related Questions