【问题标题】:Concat a php variable in a json line在 json 行中连接一个 php 变量
【发布时间】:2011-11-03 15:50:33
【问题描述】:

我在 myfile.php 中有以下内容

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

我不想输入“电子邮件”或“一些文本”,而是想将 php 变量 $thetype 和 $themsg 连接到之前的行。

我该怎么做?无论我做什么,我都会收到语法错误。

我正在尝试:

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

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

非常感谢

【问题讨论】:

    标签: php string json variables concatenation


    【解决方案1】:

    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 中不可用。

    【讨论】:

    • 不要忘记JSON_FORCE_OBJECT 选项。
    • -1,这不是他要问的...另外,您不需要将其转换为对象
    【解决方案2】:

    你的问题有点含糊……

    你在找这个吗?

    $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"}"
    

    the PHP manual for json_encode

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

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

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

    【讨论】:

    • 是否可以做类似的事情:$json_data = '{"type":"+$thetype+","msg":"+$themsg+"}';?
    • @user523129 可能,是的。但不可取。使用 Josh 的解决方案,您可以确保获得格式正确的 json 字符串。否则你很容易破坏结果。例如。使用$thetype = 'break " me';
    • 这是可能的,尽管它只是错误的。无论哪种情况,您都必须为 JSON 编码数据。在@Josh 提供的示例中,您在整个阵列上执行一次。如果您想“按照自己的方式”进行操作,则必须执行两次 - $jsonType = json_encode($theType); $jsonMsg = json_encode($theMsg); $jsonData = "{\"type\":{$jsonType},\"msg\":{$jsonMsg}}"; - 这是错误,因为您必须多次调用 json_encode() 并且必须手动构建字符串很难阅读和修改。
    • 你可以......我编辑了我的答案以展示如何。但这就是 json_encode 的设计目的
    • @binaryLV 一开始我的 addcslashes 错误。它需要两个参数,我忘记了第二个参数,它是要转义的字符列表。 我上面的示例列表对于有效的 JSON 来说还远远不够!!!
    猜你喜欢
    • 1970-01-01
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多