2

Currently I'm returning a PHP array via Ajax in the form of:

$months = array(November, December, January);

Once I return the value to Javascript I need to format it in this way for it to be compatible with a js Library I'm using:

var months = [[0, "November"], [1, "December"], [2, "January"]];

I tried returning it as an associative array from PHP and json encoding it to which I receive:

[["November"],{"1":"December"},{"2":"January"}]

Why does the index number 0 disappear once json_encoded? And also is this format the same as the one before it?

0

1 Answer 1

4

Javascript will turn associative arrays into Javscript Objects.

The easiest way to get your format would be to use this array format:

$months = array(
    array(0, 'November'), 
    array(1, 'December'),
    array(2, 'January')
);

That should return the following when it is encoded;

[[0,"November"],[1,"December"],[2,"January"]]

Edit: In terms of creating it dynamically as requested:

$months    = array(); 
$dateRange = array(
    'November' => 1000, 
    'December' => 1500, 
    'January' => 300, 
    'February' => 600
);

$counter = 0;
foreach ($dateRange as $month => $amount) { 
    $months[] = array($counter, $month);
    $counter++; 
} 

echo json_encode($months);

Output: [[0,"November"],[1,"December"],[2,"January"],[3,"February"]]

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks it works perfectly in this format. If I may ask, how would I create that array structure programatically? The way I did it was by a loop: $months = array(); $counter = 0; foreach($dateRange as $month => $amount) { $months[] = array($counter => $month); } but once I encode that, I once again am left with the format: [["November"],{"1":"December"},{"2":"January"}], that omits the 0 index and uses curly braces.
@MiguelV Updated the answer with some extra information of how you could construct it in the loop. The main thing is not to make it an associative array with $x => $y and just use $x, $y
Thanks, I was doing an associative array instead of two array items. You da best.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.