Home > front end >  how to modify array for duplicate content?
how to modify array for duplicate content?

Time:10-29

I have array codes like below, i want to duplicate "card" array like below. I have tried many way but i couldn't get any success. So where i supposed to put data2[i] to get result like i wanted? If you have any different solution for this i will be happy to hear that.

for ($i = 0; $i < 2; $i  ) {
    $data = [
        "add_order" =>
            [
                "session_id" => "",
                "company_code" => "",
                "session" => "",
                "card" => $data2[$i] = [
                    "_key_shipping" => "",
                    "_key_customer" => ["customercode" => ""],
                ],
            ],
    ];

}

$json_send = json_encode(array($data, $data2));

file_put_contents('data.json', $json_send);

and its give me this result;

[
  {
    "add_order": {
      "session_id": "",
      "company_code": "",
      "session": "",
      "card": {
        "_key_shipping": "",
        "_key_customer": {"customercode": ""}
      }
    }
  },
  [
    {
      "_key_shipping": "",
      "_key_customer": {"customercode": ""}
    },
    {
      "_key_shipping": "",
      "_key_customer": {"customercode": ""}
    }
  ]
]

but i want it like this;

[
  {
    "add_order": {
      "session_id": "",
      "company_code": "",
      "session": "",
      "card": [{
        "_key_shipping": "",
        "_key_customer": { "customercode": ""}
      },
    {
      "_key_shipping": "",
      "_key_customer": {"customercode": ""}
    },
    {
      "_key_shipping": "",
      "_key_customer": {"customercode": ""}
    }
    
  ]
}
  }
]

any idea?

CodePudding user response:

Try this way -

$data = ["add_order" =>
            [
                "session_id" => "",
                "company_code" => "",
                "session" => ""
            ],
        ];

for ($i = 0; $i < 2; $i  ) {
    $data["add_order"]["card"][] = [
                       "_key_shipping" => "",
                       "_key_customer" => ["customercode" => ""]   
                      ];

}

$json_send = json_encode(array($data));

file_put_contents('data.json', $json_send);
  • Related