如何使用PHP创建这样的JSON?我正在尝试转换动态数据并将其保存到MySQL数据库中。
{
"fbd49440-a5a1-48be-b13e-e8efddad3588": {
"0": {
"value": "dsfrasdf5464356dfs hdhfg dfgh"
}
},
"0fc71cea-5609-40a7-a1d2-b78139660f8f": {
"0": {
"value": "50"
}
},
"73936e70-4329-4aba-b47c-42c64ced420c": {
"0": {
"file": "\/components\/com_djclassifieds\/images\/item\/25_juliet_ibrahim.jpg",
"uniqid": "59a352b96773325",
"title": "",
"file2": "",
"overlay_effect": "",
"caption": "",
"width": "",
"height": ""
},
"ac00b95e-9eeb-4035-bf4a-ff206319b2d6": {
"0": {
"value": "members-in-good-standing-2014",
"text": "",
"target": "0",
"custom_title": "",
"rel": ""
}
},
"69072346-fe4c-489e-8e2b-5a7d7409fd44": {
"0": {
"value": "34"
}
}
}
我尝试了下面的代码,但它没有给我我想要的结果。
$json = (
"fbd49440-a5a1-48be-b13e-e8efddad3588"=> (
$array1
),
"0fc71cea-5609-40a7-a1d2-b78139660f8f"=> (
$array2
),
"73936e70-4329-4aba-b47c-42c64ced420c"=> (
$array3
),
"ac00b95e-9eeb-4035-bf4a-ff206319b2d6"=> (
$array4
),
"69072346-fe4c-489e-8e2b-5a7d7409fd44"=> (
$array5
)
)
echo json_encode($json);
如果有人能帮助我,我会很高兴,谢谢你
答案 0 :(得分:1)
json_encode
将获取多种类型的有效数据,并尝试将它们编码为json表示形式。它确实要求输入有效。
您粘贴的代码有多处语法错误,我们无法分辨您$array1. $array2, $array3, $array4, $array5
中的内容。但是,一些更改(并假设您的$数组是实际数组)使您的代码正常工作。
还有JSON Constants形式的位掩码选项,用于定义如何存储JSON。
$array = array( "data" => "value"); // dummy array to show data working
$json = array( //defined the following as an array
"fbd49440-a5a1-48be-b13e-e8efddad3588"=> array( //notice each of these are now defined as arrays
$array
),
"0fc71cea-5609-40a7-a1d2-b78139660f8f"=> array(
$array
),
"73936e70-4329-4aba-b47c-42c64ced420c"=> array(
$array
),
"ac00b95e-9eeb-4035-bf4a-ff206319b2d6"=> array(
$array
),
"69072346-fe4c-489e-8e2b-5a7d7409fd44"=> array(
$array
)
); //added semicolon to end the declaration
echo json_encode($json, ( JSON_FORCE_OBJECT + JSON_PRETTY_PRINT ) );
// added JSON_FORCE_OBJECT and JSON_PRETTY_PRINT
// As bitmask options, they return a constant to give `json_encode` instructions
// JSON_FORCE_OBJECT => 16, JSON_PRETTY_PRINT => 128
// JSON_FORCE_OBJECT + JSON_PRETTY_PRINT = 16 + 128 = 144
// json_encode( $array, ( JSON_FORCE_OBJECT + JSON_PRETTY_PRINT ) = json_encode ($array, 144);
返回
{"fbd49440-a5a1-48be-b13e-e8efddad3588":{"0":{"data":"value"}},"0fc71cea-5609-40a7-a1d2-b78139660f8f":{"0":{"data":"value"}},"73936e70-4329-4aba-b47c-42c64ced420c":{"0":{"data":"value"}},"ac00b95e-9eeb-4035-bf4a-ff206319b2d6":{"0":{"data":"value"}},"69072346-fe4c-489e-8e2b-5a7d7409fd44":{"0":{"data":"value"}}}
json数据中的数组数组。
如果您希望它打印每个结果的索引,那么也需要将其视为数组。足够简单,可以理解当结果中存在多个对时,结果是一对时不那么直观。
$array1 = array( "data" => "value");
echo json_encode($array1, JSON_FORCE_OBJECT );
//would return
//{"data":"value"}
$array2 = array(
array( "data" => "value" ),
array( "data" => "value" )
);
echo json_encode($array2, JSON_FORCE_OBJECT );
// would return
// {"0":{"data":"value"},"1":{"data":"value"}}
$array3 = array(
array( "data" => "value" )
);
echo json_encode($array3, JSON_FORCE_OBJECT );
// would return
// {"0":{"data":"value"}}