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}" 不幸的是,您的字符串变量是单引号。所以我们可以使用连接运算符 ('.'),returns 其左右参数的连接。

所以让我们尝试使用连接运算符;

 $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);