0

I encountered some strange error with array_filter.

My json data looks like this:

{
    "data": [
        {
            "item": "book",
            "date": "9.10."
        },
        {
            "item": "apple",
            "date": "10.10."
        },
        {
            "item": "pen",
            "date": "11.10."
        }
    ]
}

I can remove some objects with this code:

$days_arr = array('9.10.','10.10.');
    $result['data'] = array_filter($my_var['data'], function($v) use ($days_arr)
      {
        return in_array($v['date'], $days_arr);
        });
        return json_encode($result);

Which removes the objects containing a date = 9.10. and 10.10. But the problem: as soon as I use $days_arr = array('9.10.','11.10.');

My output is this:

{
    "data": {
        "0": {
            "item": "book",
            "date": "9.10."
        },
        "1": {
            "item": "pen",
            "date": "11.10"
        }
    }
}

So as you can see, some very strange error happens, the json is completely wrong formatted. 9.10. and 10.10. works, 10.10. and 11.10. destroys the output.

Who can help?

1
  • I doubt it actually happens with your given example: eval.in/877329 that being said if you do end up with indices 0,2 remaining (notice the gap) then the equivalent JSON structure will be an object and not an array Commented Oct 10, 2017 at 15:15

2 Answers 2

3

Coincidentally, your first example results in consecutive indexes starting at 0, 0 and 1 so json_encode() encodes them as dynamically assigned. The second example yields indexes 0 and 2 so it uses the hard coded values. Use array_values() to re-index:

$result['data'] = array_values($result['data']);
return json_encode($result);
Sign up to request clarification or add additional context in comments.

Comments

0

A couple of important things:

  • array_filter will preserve the keys of the elements that pass the filter
  • json_encode will preserve array keys in the output "if the keys are not a continuous numeric sequence starting from 0"

So when your $result array contains array keys 0 and 1, they are skipped in the JSON output. When it contains array keys 0 and 2 (as in your second example), they'll be preserved.

You can avoid your problem by removing the keys in the call to json_encode:

return json_encode(array_values($result));

This will keep the output in the same format as the input. See https://eval.in/877330

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.