Home > Software engineering >  How to insert a PHP variable into a second array in json?
How to insert a PHP variable into a second array in json?

Time:05-22

I have sample code:

$qty = $_POST['qty'][0];
$jsonData = array(
        'destinationLicenses' => [array(
            'mainProductId' => ''.$_POST['name'].'', // <- This works fine :) 
            'dateTo' => '2023-05-22',
            'quantity' => 1
        )]
    );

How to put the variable $qty instead of the value "1" (where "quantity" is) ?

I tried instead of 1 to add several combinations but none of them work :(

  • $qty
  • $qty;
  • '.$qty.'
  • ''.$qty.''
  • $_POST['qty'][0]
  • '.$_POST['qty'][0].'
  • ''.$_POST['qty'][0].''

I would appreciate your help in directing me to a solution.

CodePudding user response:

Okay, so the first thing is you declare an array for twice.

        'destinationLicenses' => /* HERE */ [array(
            'mainProductId' => ''.$_POST['name'].'', // <- This works fine :) 
            'dateTo' => '2023-05-22',
            'quantity' => 1
        )]

The array() is the "old" type of array declaration. You can do the same thing with [];

$jsonData = [
        'destinationLicenses' => [
            'mainProductId' => $_POST['name'],
            'dateTo' => '2023-05-22',
            'quantity' => $_POST['qty'][0],
        ]
    ];

I guess this code will be work.

By the way, the JSON array (or object) is very similar as PHP's array. If you would like to get the quantity from the JSON: jsonData['destinationLicenses'][0]['quantity']

This code is not tested, I hope it will works fine.

CodePudding user response:

The correct answer is :

$qty = $_POST['qty'][0];
$jsonData = [
'destinationLicenses' => [[
            'mainProductId' => $_POST['name'], 
            'dateTo' => '2023-05-22',
            'quantity' => (int)$qty
        ]]
    ];
  • Related