2

I could really need a help.

json_decode returns NULL.

I get the string from the POST:

$arrayOfItems = $request->getPost()->get('arrayOfItems'); 

The string looks like this:

'[{id: 161, value1: 1, value2: 1},{id: 162, value1: 2, value2: 2},{id: 163, value1: 3, value2: 3}]'

And I try to get the ids into an array:

$decodedArray = json_decode($arrayOfItems);
$ids = array();
foreach ($decodedArray as $v) {
    $ids[] = $v->id;
}

But json_decode returns NULL.

Any help is welcome.

Kind regards rholtermann

2 Answers 2

3

The keys in $arrayOfItems need to be strings for json_decode to work here. For example, the following would work:

'[{"id": 161, "value1": 1, "value2": 1},{"id": 162, "value1": 2, "value2": 2},{"id": 163, "value1": 3, "value2": 3}]'
Sign up to request clarification or add additional context in comments.

1 Comment

This is the correct answer. json_decode works according to RFC 4627 specification. Link: faqs.org/rfcs/rfc4627.html
0

There might be a couple things here. Primarily, I'm not sure that's valid JSON.

Second, if $arrayOfItems has the quotes around it in it's output, it won't work.

If you have control of the API you're requesting from, check it's output and figure out why it has the single quotes. If not, you can regex out the single quotes, but depending on your output, you should be careful with this as you might need them.

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.