Concat在json行中的php变量

ADM*_*ADM 1 php string variables json concatenation

我在myfile.php中有以下内容

$json_data = '{"type":"email","msg":"some text"}';
Run Code Online (Sandbox Code Playgroud)

我没有输入"email"或"some text",而是想将php变量$ thetype和$ themsg连接到之前的行.

我怎样才能做到这一点?无论我做什么,我都会遇到语法错误.

我尝试着:

$json_data = '{"type":"+$thetype+","msg":"+$themsg+"}';
Run Code Online (Sandbox Code Playgroud)

但正如我说错误丰富.

非常感谢

Jos*_*osh 8

你的问题有点模糊......

你在找这个吗?

$json = array('type' => $thetype, 'msg' => $themsg);
$json_data = json_encode($json);
Run Code Online (Sandbox Code Playgroud)

这将设置$json_data为类似你所描述的字符串:

<?php

$thetype = 'something';
$themsg = 'something else';
$json = array('type' => $thetype, 'msg' => $themsg);
$json_data = json_encode($json);
var_dump($json_data);
Run Code Online (Sandbox Code Playgroud)

会打印:

string(43) "{"type":"something","msg":"something else"}"
Run Code Online (Sandbox Code Playgroud)

有关json_encode的信息,请参阅PHP手册.

您可以尝试手动构建字符串,如下所示:

$json_data = '{"type":"'. addcslashes($thetype,"\"'\n").'","msg":"'. addcslashes($themsg,"\"'\n").'"}';
Run Code Online (Sandbox Code Playgroud)

但是,你通常最好使用json_encode,因为它是为此目的设计的,并且产生无效JSON的可能性要小得多.