PHP JSON Array Objects adding 0 as key



Here is my class...

class EbayItem
    public $ebayItemId;

Right before my foreach loop, I have the following:

$mainResponse = array();
$mainResponse = [
        "ack" => "success",
    "result" => []

Inside of my loop, I have...

$ebayItem = new EbayItem();
$ebayItem->ebayItemId = $itemId;
array_push($mainResponse['result'], $ebayItem);

Right after my loop I have...

echo json_encode($mainResponse);

This will produce the following:


I need it to produce...

{"ack": "success","result": [{"ebayItemId": "153532419741","ebayItemTitle": "..."}]}



You can't.

[{"ack":"success"},"result": [{"ItemId":153532419741,...},{...}]]

This is not valid JSON.

  • Objects ({}) contain"key": value pairs.
  • Arrays ([]) contain an ordered list of values.

You can't have a key ("result") in an array.

re edit:


You can't have a value without a key in an object either.

People are also looking for solutions to the problem: php - Load Laravel eloquent attribute by string


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.