我试图从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}。
通常,你会做这样的事情:
$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规范的数组。
虽然这里发布的其他答案有效,但我发现以下方法更自然:
$obj = (object) [
'aString' => 'some string',
'anArray' => [ 1, 2, 3 ]
];
echo json_encode($obj);
你只需要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);