json_encode为某些元素输出对象而不是数组

xiozqbni  于 2023-08-08  发布在  其他
关注(0)|答案(2)|浏览(92)

我有这个数组,我想把它编码成json。

Array
    [0] => Array
        [0] => . Hour
        [1] => bteam_pvp
        [2] => crackpack
        [3] => tppi
        [4] => agrarian_plus
        [5] => agrarian2
        [6] => bteam_pve
        [7] => agrarian
        [8] => horizons
        [9] => m_lobby
        [10] => m_north
        [11] => m_south
        [12] => m_east
        [13] => hub
    [1] => Array
        [0] => 24
        [1] => 91
        [2] => 81
        [3] => 64
        [4] => 98
        [5] => 72
        [6] => 37
        [8] => 63
        [9] => 93
        [10] => 59
        [11] => 92
        [12] => 67
        [13] => 98

字符串
所以我用这个:

echo '[';
foreach ($data as $row) {
    echo json_encode($row) . ",";
}
echo ']';


我得到这个结果:

[
    [". Hour","bteam_pvp","crackpack","tppi","agrarian_plus","agrarian2","bteam_pve","agrarian","horizons","m_lobby","m_north","m_south","m_east","hub"],
    {"0":24,"1":94,"2":96,"4":98,"5":82,"6":69,"8":97,"9":98,"10":96,"11":98,"12":97,"13":99}
]


你能解释一下为什么最后一个元素被编码成一个对象而不是一个数组吗?

2o7dmzc5

2o7dmzc51#

为了被编码为数组文字而不是对象,数组 * 必须 * 是非稀疏的索引数组。
在本例中,最后一个数组缺少[7],使其稀疏,因此被编码为对象。

bzzcjhmw

bzzcjhmw2#

正如你所看到的,最后一行是分配了键的数组:

{"0":24,"1":94,"2":96,"4":98,"5":82,"6":69,"8":97,"9":98,"10":96,"11":98,"12":97,"13":99}

字符串
为什么?因为你错过了关键字“3”,这是在输入中,但不是在json输出。检查你的输入数组和最后一行的键。
如果你不想编辑你的输入数组,可以这样做:

[<?php 
foreach ($gPerformance as $row) {
    echo json_encode(array_values($row)) . ",";
}
?>]

相关问题