1

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?

2
  • 2
    Add a key named orders, like $div['orders'] = array (...). And you can't have an object of objects like you want, you will have "orders": [ {}, {}, {} ] as final result. Commented Oct 26, 2020 at 19:17
  • Do you need to include the order numbers as keys? Commented Oct 26, 2020 at 23:44

2 Answers 2

1
<?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"
        }
    ]
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. I was almost close.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.