我制作的json字符串只包含在表单中输入的值。到目前为止它还不错,但唯一的问题是使得字符串的foreach函数不会从数组中获取所有项目。
让我们解释一下并展示我的代码: 如果$ title不为空,我希望我的final($ content1)字符串以该值开头。因为它有一些其他引号和花括号比其他值。与日期字段相同我也为此做了一个if,因为它还包含" date"在里面。请参阅下面的代码:
$title = "fiat titel";
$engine = "1.8";
$day = "1";
$month = "2";
$year = "1999";
$dateBuild = "02/02/1999";
// assoc array push function
function array_push_assoc($array, $key, $value){
$array[$key] = $value;
return $array;
}
$array = array();
if(!empty($title)) {
$array = array_push_assoc($array, 'title', $title);
}
if(!empty($color)) {
$array = array_push_assoc($array, 'field_modelcolor', $color);
}
if(!empty($model)) {
$array = array_push_assoc($array, 'field_carmodel', $model);
}
if(!empty($engine)) {
$array = array_push_assoc($array, 'field_modelengine', $engine);
}
if(!empty($fuel)) {
$array = array_push_assoc($array, 'field_modelfuel', $fuel);
}
if(!empty($day) && !empty($month) && !empty($year)) {
$array = array_push_assoc($array, 'field_modelyear', $dateBuild);
}
$content1 = "";
foreach($array as $ftitle => $value) {
if(empty($content1) && !empty($title)) {
$content1 = ',"' . $ftitle . '":"' . $value . '"';
}
if(!empty($day) && !empty($month) && !empty($year)) {
$content1 = ',"' . $ftitle . '":{"und":[{"value":{"date":"' . $value . '"}}]}';
}
$content1 = ',"' . $ftitle . '":{"und"[{"value":"' . $value . '"}]}';
}
$postContent = '{"type":"carmodels"' . $content1 . '}';
var_dump($array);
echo $postContent;
现在它只是回声: {"类型":" carmodels"" field_modelyear" {" UND" [{"值":&# 34; 02/02/1999"}]}}
它应该是(例子): {"类型":" carmodels"" field_modelyear" {" UND":[{"值":{ "日期":" 02/02/1999"}}]}," field_modelengine" {" UND" [{"值":" 1.6"}]}}
提前致谢!