如何格式化通过Ajax返回给javascript的php数组?

时间:2022-08-25 18:13:18

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

目前我通过Ajax返回一个PHP数组,格式为:

$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:

一旦我将值返回到Javascript,我需要以这种方式对它进行格式化,使它与我正在使用的js库兼容:

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:

我尝试将它作为一个关联数组返回,从PHP和json编码到我收到的:

[["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在json_encoded之后就消失了呢?这个格式和之前的一样吗?

1 个解决方案

#1


4  

Javascript will turn associative arrays into Javscript Objects.

Javascript将关联数组转换为Javscript对象。

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"]]

输出:[[0,“11”],[1,“12”],[2,“1月”],[3,“二月”]]

#1


4  

Javascript will turn associative arrays into Javscript Objects.

Javascript将关联数组转换为Javscript对象。

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"]]

输出:[[0,“11”],[1,“12”],[2,“1月”],[3,“二月”]]