我正在尝试从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 }。
发布于 2010-07-19 21:21:05
通常,您会这样做:
$post_data = json_encode(array('item' => $post_data));
但是,看起来您希望输出为"{}
",您最好确保通过传递JSON_FORCE_OBJECT
常量强制json_encode()
编码为object。
$post_data = json_encode(array('item' => $post_data), JSON_FORCE_OBJECT);
根据{}
规范,“JSON”括号指定一个对象,"[]
“用于数组。
发布于 2016-08-20 18:37:31
虽然这里发布的其他答案有效,但我发现以下方法更自然:
$obj = (object) [
'aString' => 'some string',
'anArray' => [ 1, 2, 3 ]
];
echo json_encode($obj);
发布于 2014-08-21 01:20:03
你只需要在你的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);
https://stackoverflow.com/questions/3281354
复制相似问题