PHP从新数组追加到JSON数组

时间:2018-07-02 19:41:12

标签: php arrays json

我在这里有一个小问题:

我要显示的是:

{"accounts":
{"n":"1001","d":"2018-06-30","u":"","e":"","r":"123112"},
{"n":"1002","d":"2018-06-30","u":"","e":"","r":"123112"}, 
{"n":"1005","d":"2018-06-30","u":"","e":"","r":"123112"}
}

一开始我有一个简单的空数据库行,没有内容。然后我要运行此脚本:

$accountff["accounts"] = array( 'n' => 1002, 
                            'd' => 2018-07-02,
                            'u' => ,
                            'e' => ,
                            'r' => );

$txid_json = json_encode($accountff, JSON_FORCE_OBJECT);

这很好,输出为:

{"accounts":{"n":1002,"d":"2018-07-02","u":"","e":"","r":""}}

但是每次我想使用此脚本添加新的“帐户”时:

  $account['n'] = $post_id;
  $account['d'] = date('Y-m-d');
  $mysqljson = json_decode($user_accounts,true);
  array_push($mysqljson['accounts'], $account); 
  $txid_json = json_encode($mysqljson, JSON_FORCE_OBJECT); 

(变量$user_accounts是保存JSON的列。)

输出为:

{"accounts":{"n":1002,"d":"2018-07-02","u":"","e":"","r":"","0":{"n":1002,"d":"2018-07-02","u":"","e":"","r":""}}}

这实际上使我发疯……我不知道“ 0”是从哪里来的。

1 个答案:

答案 0 :(得分:0)

您显示的内容不是有效的JSON。对象中的所有内容都必须为key: value对,但是除第一个对象外,您没有其他对象的键。

您似乎真的希望accounts属性是一组帐户,所以应该是:

$accountff["accounts"] = array(
    array( 'n' => 1002, 
            'd' => 2018-07-02,
            'u' => ,
            'e' => ,
            'r' => )
);

然后添加一个新帐户,您需要这样做:

$accountff["accounts"][] = $account;

等效于:

array_push($accountff["accounts"], $account);

JSON将如下所示:

{"accounts": [
    {"n":"1001","d":"2018-06-30","u":"","e":"","r":"123112"},
    {"n":"1002","d":"2018-06-30","u":"","e":"","r":"123112"}, 
    {"n":"1005","d":"2018-06-30","u":"","e":"","r":"123112"}
    ]
}

如果您使用JSON_FORCE_OBJECT,它将看起来像这样:

{"accounts": {
    "0": {"n":"1001","d":"2018-06-30","u":"","e":"","r":"123112"},
    "1": {"n":"1002","d":"2018-06-30","u":"","e":"","r":"123112"}, 
    "2": {"n":"1005","d":"2018-06-30","u":"","e":"","r":"123112"}
    }
}