Array PHP / json

1

I need to generate a JSON in the following format:

  
{
'plan_id'              => 2,
      'customer_id'          => 16,
      'payment_method_code'  => 'credit_card',
      'product_items'        => [
          [
              'product_id'        => 3
          ]
          [
              'product_id'        => 4
          ]
      ]
}

But I can not get my code in PHP:

$dados_assinatura = array(
        'plan_id'               => $plano,
        'customer_id'           => $cliente_id,
        'payment_method_code'   => 'credit_card',
        'product_items'         => array()
    );

    foreach ($array_opcionais as $produto) {
        $dados_assinatura['product_items'][][] = array (  
            'product_id' => $produto
        );
    }

The generated JSON gets:

{
   "plan_id":"60412",
   "customer_id":6527983,
   "payment_method_code":"credit_card",
   "product_items":[
      [
         {
            "product_id":"221663"
         }
      ],
      [
         {
            "product_id":"221666"
         }
      ],
      [
         {
            "product_id":"221667"
         }
      ],
      [
         {
            "product_id":"221668"
         }
      ]
   ]
}
    
asked by anonymous 06.06.2018 / 00:50

2 answers

0

You are starting an array as it seems to add products, depending on which form you should solve.

    $produtos = [
                ["product_id"=>"221663"],
                ["product_id"=>"221666"],
                ["product_id"=>"221667"],
                ["product_id"=>"221668"]
        ];
   $plano = [];
   $plano['customer_id'] = 6527983;
   $plano['payment_method_code'] = "credit_card";
   $plano['product_items'] = [];
   foreach($produtos as $produto){
      $plano['product_items'][] = $produto ;
   }
   echo json_encode($plano);
    
06.06.2018 / 01:23
0

Try this:

//inicializando arrays
$myArray = array();
$arrayProducts = array();

//montando array de produtos
foreach ($array_opcionais as $produto) {
    $arrayProducts[] = array("product_id" => $produto);
}
//formatando array
$dados_assinatura = array(
    "plan_id"               => $plano,
    "customer_id"           => $cliente_id,
    "payment_method_code"   => "credit_card",
    "product_items"         => $arrayProducts
);
//convertendo pra json
$myJson = json_encode($dados_assinatura);
    
06.06.2018 / 01:23