0

I have a array created from json

$fullResult = json_decode('[{"qid":"1", "result":"helo"}, {"qid":"2", "result":"ad"}, {"qid":"3", "result":"testing"}, {"qid":"4", "result":"dd"}]');

function filterArray($value){
    global $id;
    return ($value->qid > $id);
}

$filteredResult = array_filter($fullResult, 'filterArray');

The $id is 2

When I echo json_encode($fullResult); The result is

[   {"qid": "1", "result": "helo"},
    {"qid": "2", "result": "ad"},
    {"qid": "3", "result": "testing"},
    {"qid": "4", "result": "dd"}    ]

However, when I echo json_encode($filteredResult); the result as below (e.g. having the additional index.

{  "2":{"qid":"3","result":"testing"},
   "3":{"qid":"4","result":"dd"}   }

I want it to be as below instead

[  {"qid":"3","result":"testing"},
   {"qid":"4","result":"dd"}   ]

How could I achieve that?

Elye
  • 53,639
  • 54
  • 212
  • 474

3 Answers3

1

array_filter will retain the key. If you want to make it a simple array, you can use array_values

$filteredResult = array_values(array_filter($fullResult, 'filterArray'));

echo json_encode($filteredResult); 

This will result to:

[{"qid":"3","result":"testing"},{"qid":"4","result":"dd"}] 

Doc: array_values

Eddie
  • 26,593
  • 6
  • 36
  • 58
1

Instead of

echo json_encode($filteredResult);

try something along the lines of,

echo json_encode(array_values($filteredResult));

array_values would eliminate the unwanted indexes.

Manav
  • 1,357
  • 10
  • 17
0

You can set it by loop also.

$singleArray = array();

foreach ($filteredResult as $key => $value){
        $singleArray[] = $value;
}
echo json_encode($singleArray);exit;
Virb
  • 1,639
  • 1
  • 16
  • 25