【问题标题】:(PHP) Problem inserting variables in array(PHP) 在数组中插入变量的问题
【发布时间】:2022-01-28 03:00:40
【问题描述】:

我在数组中插入变量时遇到问题。这是数组:

        [
            'body' => '{"data":{"attributes":{"details":{"card_number":"4343434343434345","exp_month":12,"exp_year":24,"cvc":"123"},"billing":{"name":"Test Man ","email":"test@test.com","phone":"1234567"},"type":"card"}}}',
            'headers' => [
                'Accept' => 'application/json',
                'Authorization' => 'Basic c2tfdGVzdF9mcUNRUmd4NVVUOEJhRHhEYnNHM2lOVm86',
                'Content-Type' => 'application/json',
            ],
        ]

我需要做的是将card_number、exp_month、exp_year 等替换为用户提交的值。我尝试了很多方法来替换像这样的值:

        [
            'body' => '{"data":{"attributes":{"details":{"card_number":"{$request->cardNumber}","exp_month":{$request->cardMonth},"exp_year":{$request->cardyear},"cvc":"{$request->cardCVC}"},"billing":{"name":"{$request->name}","email":"{$request->email}","phone":"{$request->phone}"},"type":"card"}}}',
            'headers' => [
                'Accept' => 'application/json',
                'Authorization' => 'Basic c2tfdGVzdF9mcUNRUmd4NVVUOEJhRHhEYnNHM2lOVm86',
                'Content-Type' => 'application/json',
            ],
        ]

不幸的是,没有读取变量。任何帮助表示赞赏。谢谢。

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    双引号字符串最重要的特点是变量名会被扩展。有关详细信息,请参阅字符串解析。 https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double

    要么使用双引号字符串,要么转义额外的双引号,例如:

    [
    'body' => "{\"data\":{\"attributes\":{\"details\":{\"card_number\":\"{$request->cardNumber}\",\"exp_month\":{$request->cardMonth},\"exp_year\":{$request->cardyear},\"cvc\":\"{$request->cardCVC}\"},\"billing\":{\"name\":\"{$request->name}\",\"email\":\"{$request->email}\",\"phone\":\"{$request->phone}\"},\"type\":\"card\"}}}"
    ]
    

    或者使用单引号连接多个字符串

    [
    'body' => '{"data":{"attributes":{"details":{"card_number":"' . $request->cardNumber . '","exp_month":' . $request->cardMonth . '},"exp_year":' . $request->cardyear . ',"cvc":"' . $request->cardCVC . '"},"billing":{"name":"' . $request->name . '}","email":"' . $request->email . '","phone":"' . $request->phone . '"},"type":"card"}}}'
    ]
    

    【讨论】:

    • 第二个最适合我。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 2015-10-21
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    相关资源
    最近更新 更多