1

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.

2
  • why you need json list instead of json object? Commented Mar 10, 2015 at 20:52
  • this list that you have.. it looks like a PHP array. Is that what it is? You are calling it "list", just be specific. Commented Mar 10, 2015 at 21:15

1 Answer 1

5

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'};
Sign up to request clarification or add additional context in comments.

1 Comment

Yes.. I knew that but still there was hope ! Thanks anyway !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.