嵌套的json字符串,带有php中的变量

时间:2016-01-14 11:33:47

标签: php json variables quotes

我不会欺骗你们:我讨厌嵌套阵列。

所以不是我的[工作]代码

$query_array = Array(
    "fields" => Array ("timestamp", "user.raw", "mailbox", "verb", "backend"),
    "size"   => 1,
    "sort"   => Array (Array ("@timestamp" => Array ("order" => $varOrder))),
    "query"  => Array (
        "bool" => Array (
            "must" => Array (
                Array ("match" => Array ("verb"    => "open")),
                Array ("term"  => Array ($varField => $varValue))
            )
        )
    )
);

我想使用下面的[不工作]代码

$query_json_string = '{
    "fields" : [ "timestamp", "user.raw", "mailbox", "verb", "backend" ],
    "size"   : 1,
    "sort"   : [ { "@timestamp" : { "order" : $varOrder } } ],
    "query"  : {
        "bool": {
            "must": [
                { "match" : { "verb"    : "open" } },
                { "term"  : { $varField : $varValue } }
            ]
        }
    }
}';

维护起来容易得多......

但在单引号内,变量varOrdervarFieldvarValue永远不会扩展(我相信)。

如何在这个漂亮干净的json字符串中使用变量?

3 个答案:

答案 0 :(得分:1)

JSON基本上是Javascript的关联数组版本。

$query_array = Array(
    "fields" => Array ("timestamp", "user.raw", "mailbox", "verb", "backend"),
    "size"   => 1,
    "sort"   => Array (Array ("@timestamp" => Array ("order" => $varOrder))),
    "query"  => Array (
        "bool" => Array (
            "must" => Array (
                Array ("match" => Array ("verb"    => "open")),
                Array ("term"  => Array ($varField => $varValue))
            )
        )
    )
);

$query_json_string = json_encode($query_array);

但如果您遇到问题,那么heredoc语法应该对您有用..

$query_json_string = <<<JSON
{
    "fields" : [ "timestamp", "user.raw", "mailbox", "verb", "backend" ],
    "size"   : 1,
    "sort"   : [ { "@timestamp" : { "order" : $varOrder } } ],
    "query"  : {
        "bool": {
            "must": [
                { "match" : { "verb"    : "open" } },
                { "term"  : { $varField : $varValue } }
            ]
        }
    }
}
JSON;

// if you wanted PHP array,
$query_array = json_decode($query_json_string, true);

答案 1 :(得分:1)

据我了解你的问题,你只是不开心使用php的数组语法。如果是这种情况,则不要使用语法。而是使用简单的方括号,自5.4版本开始提供。

这样做,您的最终代码可能是:

$query = [
    "fields" => ["timestamp", "user.raw", "mailbox", "verb", "backend"],
    "size"   => 1,
    "sort"   => [["@timestamp" => ["order" => $varOrder]]],
    "query"  => [
        "bool" => [
            "must" => [
                ["match" => ["verb"    => "open"]],
                ["term"  => [$varField => $varValue]]
            ]
        ]
    ]
];

哪个与你想要的语法相差甚远。唯一的区别是=>而不是:。但是还有一个额外的好处,就是不需要用{}声明对象

答案 2 :(得分:0)

您可以将单引号切换为双引号并转义双引号

in_memory