Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_encode with a different result after array_filter

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.

like image 383
Johannes Avatar asked Apr 05 '13 12:04

Johannes


People also ask

What does json_encode return?

The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.

What does json_encode mean?

The json_encode() function is used to encode a value to JSON format.

What is json_encode and Json_decode?

JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.

How can I get JSON encoded data in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.


1 Answers

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);
like image 181
Baba Avatar answered Sep 18 '22 12:09

Baba