0

我像这样构建长字符串:(你如何在 php 中调用它?))

$json = <<< JSON
{
   "campaign": {
    "name": "$campaign_name",
    "state": "$state",
    "advertiser_id": $advertiser_id,
    "line": $line,
    "daily_budget": $daily_impression,
    "pacing": $pacing_selected,
    "cpm_type": "$bittype"
    }
}
JSON;

所有变量都设置了值,但现在我需要添加逻辑并检查例如 $campaign_name 是否不为空,如果它为空,请不要在此字符串间接添加字符串:

 "name": "$campaign_name",

其他变量也一样。我怎么能在这个字符串生成器中做到这一点?

4

2 回答 2

6

不要手动编写 JSON。这只是灾难的秘诀。先创建数组,然后将其转换为 JSON。

$data = array();

if( !empty( $campaign_name ) ) {
    $data[ "name" ] = $campaign_name;
}
// you might want to make a better system than checking each variable individually,
// but this is the general idea

$json = json_encode( array( "campaign" => $data ) );
于 2013-08-02T07:26:42.967 回答
4

在外面做逻辑,只包含一个变量

$campaign_name_JSON = "";
if (!empty($campaign_name))
   $campaign_name_JSON = '"name": "'.$campaign_name.'",';

$json = <<< JSON
{
   "campaign": {
    $campaign_name_JSON
    "state": "$state",
    "advertiser_id": $advertiser_id,
    "line": $line,
    "daily_budget": $daily_impression,
    "pacing": $pacing_selected,
    "cpm_type": "$bittype"
    }
}
JSON;

但是你最好在 php 中构建数据结构然后 json_encoding 它

于 2013-08-02T07:26:26.133 回答