You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP执行向数组追加元素后properties字段格式异常问题咨询

问题原因
  • 你操作properties字段的逻辑错误:原properties是索引数组,每一项才是包含property和value的子数组,你直接给properties层级追加字符串键,破坏了原有索引数组结构,PHP的json_encode遇到包含非数字索引、或者索引不连续的数组时,会自动转为JSON对象格式,也就出现了你看到的数字键问题。
  • array_values用错了作用对象:你只重置了外层nodes数组的索引,完全没有处理出问题的properties数组,解决不了格式错误。
修正后的代码
<?php

    header("Access-Control-Allow-Origin: *");

    $nodeId = $_POST['nodeId'];
    $addNodeProperty = $_POST['addNodeProperty'];
    $addNodeValue = $_POST['addNodeValue'];

    $json = file_get_contents("../data/data.json");
    $data = json_decode($json, true);

    $nodes = $data['nodes'];

    $nodeIdInArray = array_search($nodeId, array_column($nodes, 'id'));

    // 正确写法:给properties索引数组追加新元素,而不是直接给properties加键
    $nodes[$nodeIdInArray]['properties'][] = [
        'property' => $addNodeProperty,
        'value' => $addNodeValue
    ];

    // 手动重置properties索引,确保是连续索引数组,转JSON就会输出[]格式
    $nodes[$nodeIdInArray]['properties'] = array_values($nodes[$nodeIdInArray]['properties']);

    $data['nodes'] = $nodes;

    // 加JSON_UNESCAPED_UNICODE参数可避免中文/特殊字符转Unicode编码,按需开启即可
    $json = json_encode($data, JSON_UNESCAPED_UNICODE);

    file_put_contents("../data/data.json", $json);

?>

内容的提问来源于stack exchange,提问作者ICoded

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 08:57:03