10

I want json_encode to return something like this

[{key: "value"},{key:"value"},...]

Instead I get something like this:

{"1": {key: "value"}, "2": {key: "value"}, ...}

The result was fine until I did an array_filter... Strange...

function somefunction($id, $ignore = array()) {
    $ignorefunc = function($obj) use ($ignore) {
        return !in_array($obj['key'], $ignore);
    };

    global $db;

    $q = "Some query";

    $rows = $db->giveMeSomeRows();
    $result = array();
    if ($rows) {
        // this mapping I've always done
        $result = array_map(array('SomeClass', 'SomeMappingFunction'), $rows);
        if (is_array($ignore) && count($ignore) > 0) {
            /////// PROBLEM AFTER THIS LINE ////////
            $result = array_filter($result, $ignorefunc);
        }
    }
    return $result;
}

So again, if I comment out the array_filter I get what I want from json_encode on whatever somefunction returns, if not I get an JSON-Object.

If I var_dump $result before and after array_filter it's the same type of PHP-array, no strings in the keys and so on.

1 Answer 1

14

You want an array but you are getting json object because your array does not start from 0 trying using array_values to reset the array

Example

$arr = array(1=>"a",2=>"Fish");
print(json_encode($arr));
print(json_encode(array_values($arr)));

Output

{"1":"a","2":"Fish"}
["a","Fish"]

Replace

 $result = array_filter($result, $ignorefunc);

With

  $result = array_filter($result, $ignorefunc);
  $result = array_values($result);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Baba for the answer, i was having a similar issue and this resolved it!

Your Answer

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