在json行中连接一个php变量


Concat a php variable in a json line

我在myfile.php中有以下内容

$json_data = '{"type":"email","msg":"some text"}';

我想把php变量$thetype和$themsg连接到前一行,而不是输入"email"或"some text"。

我该怎么做呢?不管我怎么做,都会出现语法错误。

我在:

$json_data = '{"type":"+$thetype+","msg":"+$themsg+"}';

但正如我所说,错误很多。

Thanks to lot

你的问题有点模糊…

你在找这个吗?

$json = array('type' => $thetype, 'msg' => $themsg);
$json_data = json_encode($json);

$json_data设置为您所描述的字符串:

<?php
$thetype = 'something';
$themsg = 'something else';
$json = array('type' => $thetype, 'msg' => $themsg);
$json_data = json_encode($json);
var_dump($json_data);

打印:

string(43) "{"type":"something","msg":"something else"}"

json_encode参见PHP手册

你可以尝试手工构建字符串,像这样:

$json_data = '{"type":"'. addcslashes($thetype,"'"''n").'","msg":"'. addcslashes($themsg,"'"''n").'"}';

但是,您通常最好使用json_encode,因为它是为此目的而设计的,并且不太可能产生无效的JSON。

PHP有一个编码json的函数。但是,您需要将其作为对象输出以保存密钥。顺便说一下,这是一个3D数组。

$data[]=array('type' => $thetype0, 'msg' => $themsg0);
$data[]=array('type' => $thetype1, 'msg' => $themsg1);
$json=json_encode((object)$data);

编辑:此方法应用于较旧的PHP版本。它与PHP 5.3兼容。json_encode()函数做了一些修改,使得对象输出在PHP 5.2中不可用。