Reputation: 75
I am in a unique fix. It is easy but for the love of god I havent able to figure it out.
Code
// Loop through results
for($k=0;$k<count($orderNumber);$k++) {
// Add a new array for each iteration
$div[] = array (
$orderNumber[$k]=>array(
"customerOrderId"=>$orderNumber[$k],
"status"=>$orderStatus[$k],
"readyTime"=>$orderShipDate[$k]
));
}
Returns
[
{}
{}
{}
]
I although need the API to return in the following format.
"orders" : {
{}
{}
{}
}
Can someone guide me in the correct direction?
Upvotes: 1
Views: 58
Reputation: 75
Thank you to all of you who helped me. This is what I ended up with and works perfectly as I need.
for($k=0;$k<count($orderNumber);$k++) {
// Add a new array for each iteration
$div['orders'][$orderNumber[$k]] = array (
"customerOrderId"=>$orderNumber[$k],
"status"=>$orderStatus[$k],
"readyTime"=>$orderShipDate[$k]);
}
Upvotes: 0
Reputation: 7485
<?php
$orderNumber = ['10', '23'];
$orderStatus = ['pending', 'shipped'];
$orderShipDate = ['2023', '2019'];
for($k=0;$k<count($orderNumber);$k++) {
$div['orders'][$orderNumber[$k]] = array (
"customerOrderId"=>$orderNumber[$k],
"status"=>$orderStatus[$k],
"readyTime"=>$orderShipDate[$k]
);
}
echo json_encode($div, JSON_PRETTY_PRINT);
Output:
{
"orders": {
"10": {
"customerOrderId": "10",
"status": "pending",
"readyTime": "2023"
},
"23": {
"customerOrderId": "23",
"status": "shipped",
"readyTime": "2019"
}
}
}
If you drop the order keying for a sequential append you'll get a list output:
$div['orders'][] = array (
Output (with the line above swapped in):
{
"orders": [
{
"customerOrderId": "10",
"status": "pending",
"readyTime": "2023"
},
{
"customerOrderId": "23",
"status": "shipped",
"readyTime": "2019"
}
]
}
Upvotes: 1