How do I get php `json_encode` to return a Javascript array instead of a Javascript object?

I have an array in PHP that contains a list of objects:

// This is a var_dump of $data

array(3911) {
  [0]=>
  object(stdClass)#44 (3) {
    ["ID"]=>
    string(1) "1"
    ["name"]=>
    string(9) "Forest"
  }
  [1]=>
  object(stdClass)#43 (3) {
    ["ID"]=>
    string(1) "2"
    ["Name"]=>
    string(3) "Lt. Dan"
  }

  // etc ...
}

I convert this array to an array with flat indices:

$return = [];
$length = count($data);
$return = array_fill(0, $length, null);

// Convert list into flat array
foreach ( $data as $item ){
  $return[(int)$item->ID] = $item->name;
}

header( 'Content-Type: application/json' );
echo json_encode( $return );

The result that I get with json_encodeis a list of objects:

{"0":null,"1":"Forest","2":"Lt. Dan","3":"Bubba","4":"Jenny"}

What I expect to receive:

[null,"Forest","Lt. Dan","Bubba","Jenny"]

How do I get json_encodeto return a Javascript array instead of a Javascript object?


Side Note : The manual states that:

When encoding an array, if the keys are not a continuous numerical sequence starting from 0, all keys are encoded as strings and are explicitly specified for each value-value pair.

But my array is a continuous set, so I use array_fill.

+4
2

, count($data) , . , $data 1, 2, 3 5; array_fill 0-3 $return, .

:

$return = [];
$length = max(array_keys($data));
$return = array_fill(0, $length, null);
0

UPDATE

:

, . null.

, $data , max(ID) + 1 , . IMHO, , . , null s. JS , ( PHP ).


$data , , :

json_encode , , JSON. - :

echo json_encode( array_values($return) );
+4

All Articles