添加文本的正确方式+;json字符串中的php变量?

添加文本的正确方式+;json字符串中的php变量?,php,json,Php,Json,我正在努力找到在json字符串中添加php变量的正确方法,在变量前面添加文本。这就是我到目前为止得到的 $postData = ' { "message": "Web order '.$order_number.'" } '; 当我查看打印输出时,在“Web订单”之后有一个换行符,但除此之外似乎没有任何问题。。。这样做吗?如果要使用json字符串,请确保已正确使用数组中的值 示例: <? $order_number = 1; $yourArray = array(

我正在努力找到在json字符串中添加php变量的正确方法,在变量前面添加文本。这就是我到目前为止得到的

  $postData = '
  {
    "message": "Web order '.$order_number.'"
  }
  ';

当我查看打印输出时,在“Web订单”之后有一个换行符,但除此之外似乎没有任何问题。。。这样做吗?

如果要使用json字符串,请确保已正确使用数组中的值

示例:

<?
$order_number = 1;
$yourArray = array('message'=>"Web order ".$order_number);
echo json_encode($yourArray);
?>
{"message":"Web order 1"}
这里,我将数组用于数据
$yourray
,然后用于json字符串


如果要使用json字符串,请确保已正确使用数组中的值

示例:

<?
$order_number = 1;
$yourArray = array('message'=>"Web order ".$order_number);
echo json_encode($yourArray);
?>
{"message":"Web order 1"}
这里,我将数组用于数据
$yourray
,然后用于json字符串


使用
sprintf()
直接处理Json很快就会变得非常有害。更喜欢使用array然后
json\u encode

在您的案例中,以下是一个简单的示例:

$message = sprintf('Web order %s', $order_number)
$postData = [
  'message' => $message
];

$json = json_encode($postData);

使用
sprintf()
直接处理Json很快就会变得非常有害。更喜欢使用array然后
json\u encode

在您的案例中,以下是一个简单的示例:

$message = sprintf('Web order %s', $order_number)
$postData = [
  'message' => $message
];

$json = json_encode($postData);

是的,首先使用
json\u decode
解码json,然后在对象/数组中添加任何您想要添加的内容(取决于您是将其解码为对象还是数组),然后对其重新编码。
json\u编码(数组('message'=>“Web order.”$order\u number))
一目了然。您确信
$order\u number
包含可以转换为字符串的值吗?是的,首先使用
json\u decode
解码json,然后在对象/数组中添加任何您想要添加的内容(取决于您是将其解码为对象还是数组),然后对其重新编码。
json\u编码(数组('message'=>“Web order”。$order\u number))
乍一看应该是这样的。您确信
$order\u number
包含可以转换为字符串的值吗?