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.
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.
The json_encode() function is used to encode a value to JSON format.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With