Newwt Newwt - 4 months ago 20
JSON Question

json_encode returns column name and array index

I'm having a small issue with my code. What I want to do is show the results of a select as json. This is how I do it:

foreach ($query as $row) {
$test = json_encode($row);
}


But it returns that:

{0: "34.8", 1: "1441098255", 2: "1", col1: "34.8", col2: "1441098255", col3: "1"}


And I want it like this:

{0: "34.8", 1: "1441098255", 2: "1"}


Or this:

{col1: "34.8", col2: "1441098255", col3: "1"}


I tried doing what they say here, but to no avail.

Answer Source

Use array_filter with ARRAY_FILTER_USE_KEY flag

$keys = ["col1", "col2", "col3"];
foreach ($query as $row) {
    $filtered = array_filter((Array) $row, function($key) use($keys) {
        return in_array($key, $keys);
    }, ARRAY_FILTER_USE_KEY);
    $test = json_encode($filtered);
}

Notice: If your $row is array not object you don't need to cast it to array (Array) $row