I've been wondering if it's possible to force json_encode into returning Array instead an Object while still keeping the "integer" index.
What am I trying to achieve if you're asking is an array of usernames ( with their userID's as keys in the array ).
So if I have a list of mutual friends like this in PHP:
1 => 'John Doe',
2 => 'Jane Doe',
5 => 'Oliver Natefield',
11 => 'Chris Cole'
I'd like to use json_encode and I tried two methods.
First one is by simply adding into an empty PHP Array, values to their respective index ( userID ).
<?php
$list = array( );
foreach ( $friends as $userID => $name )
$list[ $userID ] = $name;
echo json_encode( $list );
?>
That creates me an Object sadly. Ok, then I tried something else...
<?php
$list = array( );
foreach ( $users as $userID => $name )
array_splice( $list, $userID, 0, $name );
echo json_encode( $list );
?>
Again, failed, this time, it's an Array, but the indexes are not taken into consideration.
I know that.. the array should be like :
undefined, // userID 0
'John Doe', // userID 1
'Jane Doe', // userID 2
undefined, // userID 3
undefined, // userID 4
'Oliver Natefield', // userID 5
undefined, //userID 6
undefined, // etc
But... if I have a friend with userID with the index 1504 .. shouldn't there be a memory downside ?
And while we're at it, can I see how much memory does an array of 1000 undefined elements use ? It's relevant because if it consumes too much memory, I'll just have to search through an array of objects for a username after a specific userID.