1

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?

0

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

8 Comments

This is not work for me i didn't get above result what i mentioned
@imp I have edited my answer. Can you try now
i have check and try it but "card" array must below add_order array and it must be subarray. But your codes make new array for "card"
@imp sorry I misunderstood first. Now i got it. I have corrected my code.
now it's worked! Really appreciate for your help.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.