[英]create json using json_encode in php
i have the following code, which does some tasks, and returns dates:我有以下代码,它执行一些任务并返回日期:
<?php
if (valid value]):
echo "some data";
print format_date() . '-';
if (second test) print format_date(); // prints 01/09/2020
else print format_date(); // prints 10/09/2020
echo "valid until";
print format_date(...); // prints 14/09/2020
endif;
desired json:所需 json:
[
{status: 'some data', dates: { from: '01/09/2020', to: '10/09/2020'}, til: {label: 'valid until', date: 'Fri 14/09/2020'}}
]
whatever i tried, gets me to create a json array, while i need the above structure, how should i alter the above code?无论我尝试什么,都会让我创建一个 json 数组,而我需要上面的结构,我应该如何更改上面的代码?
I'm not sure if I understood your problem correctly, but this is how you can encode an array to JSON.我不确定我是否正确理解你的问题,但这是你如何将数组编码为 JSON。
<?php
$myArray = [];
if(1 == 1) $myArray["test"] = "1 is equal to 1";
if(1 !== 2) $myArray["test2"] = "1 is not equal 2";
print_r(json_encode($myArray, true));
Output: {"test":"1 is equal to 1","test2":"1 is not equal 2"}
Output: {"test":"1 is equal to 1","test2":"1 is not equal 2"}
The array is defined at the beginning and is then filled.数组在开始时被定义,然后被填充。 At the end it is encoded with json_encode and output.最后用 json_encode 和 output 编码。
This should be the code what you need:这应该是您需要的代码:
<?php
$myArray = []; # This array is filled below and encoded to json at the end
if(1 == 1) { # Your if-statement
$myArray["status"] = 'some data';
$dates = []; # This array is the "dates" array
$dates["from"] = "Date 1";
if(1 == 2){ # Your second if-statement
$dates["from"] = "Date 2";
}else {
$dates["to"] = "Date 3";
}
$myArray["dates"] = $dates; # Add the "dates" array to your main array
$myArray["til"] = [
"label" => "valid until",
"date" => "Date 4",
];
}
$json = json_encode($myArray, true); # Parse your array to json
print_r($json);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.