PHP JSON Array Objects adding 0 as key

166

UPDATED QUESTION

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:

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

I need it to produce...

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

Answer

Solution:

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:

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

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

Source

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.