繁体   English   中英

PHP:将变量添加到json_decode

[英]PHP: add variables into json_decode

我想将变量添加到 php 中的字符串中。我用谷歌搜索并找到了方法:“{$a}”。 但是,这对我不起作用。 我回应了它,它实际上回应了“{$a}”而不是变量的实际值。 这是我的代码:

$body= json_decode(
                            '{
                                "sender_batch_header":
                                {
                                  "email_subject": "SDK payouts test txn"
                                },
                                "items": [
                                {
                                  "recipient_type": "EMAIL",
                                  "receiver": "{$email}",
                                  "note": "Your 1$ payout",
                                  "sender_item_id": "Test_txn_12",
                                  "amount":
                                  {
                                    "currency": "CHF",
                                    "value": "{$actualAmount}" 
                                  }
                                }]
                              }',             
                            true);

这是 $body 的回声:

{ "sender_batch_header": { "email_subject": "SDK payouts test txn" }, "items": [ { "recipient_type": "EMAIL", "receiver": "{$email}", "note": "Your 1 $ payout", "sender_item_id": "Test_txn_12", "amount": { "currency": "CHF", "value": "{$actualAmount}" } }] }

我所说的变量是 $email 和 $actualAmount。 我调试了它,它们都有一个值,只是没有添加到字符串中。 谁能帮忙?

字符串文字可以有不同的方式:

您可以在双引号字符串中使用大括号,例如: "Hello {$foo}"不幸的是,您的字符串变量是单引号。 所以我们可以使用连接运算符('.'),它返回其左右连接的 arguments。

因此,让我们尝试使用连接运算符;

 $body= json_decode(
                                '{
                                    "sender_batch_header":
                                    {
                                      "email_subject": "SDK payouts test txn"
                                    },
                                    "items": [
                                    {
                                      "recipient_type": "EMAIL",
                                      "receiver": "'.$email.'",
                                      "note": "Your 1$ payout",
                                      "sender_item_id": "Test_txn_12",
                                      "amount":
                                      {
                                        "currency": "CHF",
                                        "value": "'.$actualAmount.'" 
                                      }
                                    }]
                                  }',             
                                true);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM