PHP array / json

Asked

Viewed 56 times

1

I need to generate a JSON in the following format below:

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

But I can’t with my PHP code:

$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 is:

{
   "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"
         }
      ]
   ]
}
  • 1

    Yes, because there is no JSON syntax ['product_id' => 4]. If it is associative data, it will be an object, with {}. Brackets are for lists only.

2 answers

0

You are starting an array the more it seems when adding the products, second way must 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);

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.