Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I convert PHP Associative Arrays to JSON?

I’m trying to convert a small JSON to PHP Associative Arrays, but I’m missing a simple thing. Please check the following:

JSON to convert:

    $data = '{
        "intent": "CAPTURE",
        
        "purchase_units": [{
              "amount": {
                "currency_code": "EUR",
                "value": "211.00",
              }
        }],     
    }';

My wrong PHP Associative Arrays:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$data = array(
    "intent" => "CAPTURE",
    "purchase_units" => array(
        "amount" => array(
            "currency_code" => "EUR",
            "value" => "211.00",
        ),
    ),
);

My PHP code doesn’t let me pass this JSON, there must be a small thing I’m missing. Please could you help?

Thank you very much!

>Solution :

The value of purchase_amounts should be an array of associative arrays.

$data = array(
    "intent" => "CAPTURE",
    "purchase_units" => array(array(
        "amount" => array(
            "currency_code" => "EUR",
            "value" => "211.00",
        ),
    )),
);

Since PHP allows you to use [] notation for array literals, the simplest way to do this is to just copy the JSON. Replace {} with [] and : with =>

$data = [
        "intent" => "CAPTURE",
        
        "purchase_units" => [[
              "amount" => [
                "currency_code" => "EUR",
                "value" => "211.00",
              ]
        ]],     
    ];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading