Reputation: 3576
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
.
Upvotes: 1
Views: 1310
Reputation: 360662
This is not really possible. It's a restriction of Javascript syntax, which is basically what JSON is. You can't specify array keys in a Javascript "shortcut" array definition, like you can with PHP. e.g.
$foo = array(1 => 'a', 10 => 'b');
There's no such notation in JS, the only shortcut allowed is
foo = ['a', 'b'];
which would give you the PHP equivalent 0 => 'a', 1 => 'b'
. To use non-sequential array keys, you MUST use an Object:
foo = {1: 'a', 10: 'b'};
Upvotes: 5