我在将多维 PHP 数组转换为 JSON 时遇到了一些麻烦。我用 json_encode 转换它,但它变成 null。
我正在尝试开发一个 orgChart,数据从 CSV 文件中读取并保存在一个数组中。布局和 JS 代码是为接收 JSON 文件而构建的,因此我需要该格式的文件。
这是数组的一个切片,里面包含了175个数组
Array
(
[2] => Array
(
[id] => 1
[nome] => ELOTECH
[cargo] => ""
[idcargo] => 1
[pai] => 0
)
[3] => Array
(
[id] => 10
[nome] => Departamento Pessoal
[cargo] =>
[idcargo] => 10
[pai] => 1
)
[4] => Array
(
[id] => 20
[nome] => Comercial
[cargo] =>
[idcargo] => 20
[pai] => 1
)
)
我正在使用 json_encode 将数组转换为 JSON OBS: *** $colab 是由 CSV 提供的数组名称
$dados_json = json_encode($colab);
$fp = fopen("jsonOrgan.json", "w");
$write = fwrite($fp, $dados_json);
fclose($fp);
我需要它在 JSON 上输出如下:
[{
"id": 1,
"cargo": "ELOTECH",
"nome": "",
"idcargo": 1,
"pai": 0
}]
但是它返回null
以下是我如何从 CSV 文件创建数组。
while ($line = fgetcsv($save, 1000, ";")) {
if ($linha++ == 0) {
continue;
}
$colab[$linha] = [
'id' => $line[0],
'nome' => $line[1],
'cargo' => $line[4],
'idcargo' => $line[0],
'pai' => $line[5],
];}
最佳答案
在 Roger Russel 的指导下,我的问题得到了解决。
JSON 由于编码而变为 NULL。 我使用了 uft8_encode 并解决了这个问题。 然后我更改了数组创建以适应我需要 JSON 文件的模式。
我正在使用计数器作为索引创建数组,如下所示:
$colab[$linha] = [
'id' => $line[0],
'nome' => $line[1],
'cargo' => $line[4],
'idcargo' => $line[0],
'pai' => $line[5],
]
然后改成不传索引就创建:
$colab[] = [
'id' => $line[0],
'nome' => $line[1],
'cargo' => $line[4],
'idcargo' => $line[0],
'pai' => $line[5],
]
就这样,我的问题解决了!
谢谢!
关于javascript - 将 Array Php 转换为 JSON 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53287037/