以正确的方式创建JSON对象

问题描述 投票:91回答:3

我试图从PHP数组中创建一个JSON对象。该数组如下所示:

$post_data = array('item_type_id' => $item_type,
    'string_key' => $string_key,
    'string_value' => $string_value,
    'string_extra' => $string_extra,
    'is_public' => $public,
    'is_public_for_contacts' => $public_contacts);

编码JSON的代码如下所示:

$post_data = json_encode($post_data);

JSON文件最终应该看起来像这样:

{
    "item": {
        "is_public_for_contacts": false,
        "string_extra": "100000583627394",
        "string_value": "value",
        "string_key": "key",
        "is_public": true,
        "item_type_id": 4,
        "numeric_extra": 0
    }
} 

如何将创建的JSON代码封装在“item”中:{JSON CODE HERE}。

php json
3个回答
142
投票

通常,你会做这样的事情:

$post_data = json_encode(array('item' => $post_data));

但是,由于您似乎希望输出为“{}”,因此最好通过传递json_encode()常量来强制JSON_FORCE_OBJECT编码为对象。

$post_data = json_encode(array('item' => $post_data), JSON_FORCE_OBJECT);

{}”括号指定一个对象,“[]”用于根据JSON规范的数组。


49
投票

虽然这里发布的其他答案有效,但我发现以下方法更自然:

$obj = (object) [
    'aString' => 'some string',
    'anArray' => [ 1, 2, 3 ]
];

echo json_encode($obj);

25
投票

你只需要php数组中的另一个图层:

$post_data = array(
  'item' => array(
    'item_type_id' => $item_type,
    'string_key' => $string_key,
    'string_value' => $string_value,
    'string_extra' => $string_extra,
    'is_public' => $public,
   'is_public_for_contacts' => $public_contacts
  )
);

echo json_encode($post_data);
© www.soinside.com 2019 - 2024. All rights reserved.