Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5

Thread: json_encode

  1. #1
    Regular Coder
    Join Date
    Sep 2004
    Posts
    713
    Thanks
    6
    Thanked 2 Times in 2 Posts

    json_encode

    i think php json_encode function is handy, however now i got a problem, i have one array

    $array[0]="a";
    $array[1]="b";
    $array[2]="c";

    when we do json_encode, we got

    ["a","b","c"]

    however i do need json_encode in this way
    {"0":"a","1":"b","2":"c"}

    what shall we do?
    flying dagger

  • #2
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    The desired format is an object, and I don't believe object keys can be enumerated. Miht be wrong though, I'm no JavaScript super-guru.

  • #3
    Senior Coder
    Join Date
    Apr 2007
    Location
    Quakertown PA USA
    Posts
    1,028
    Thanks
    1
    Thanked 125 Times in 123 Posts
    If I'm not mistaken, it's because you are using numeric indices in your array. If you change them to strings, json_encode should give what you're looking for.
    John

  • #4
    Regular Coder
    Join Date
    Sep 2004
    Posts
    713
    Thanks
    6
    Thanked 2 Times in 2 Posts
    the problem is i need integer.
    flying dagger

  • #5
    bdl
    bdl is offline
    Regular Coder
    Join Date
    Apr 2007
    Location
    Camarillo, CA US
    Posts
    590
    Thanks
    4
    Thanked 83 Times in 82 Posts
    You don't have to use json_encode().
    PHP Code:
    $array= array(
     
    'A''B''C'
    );

    $jsonString'{ ';
    foreach(
    $array AS $key => $val) {
      
    $jsonString.= "'{$key}' : '{$val}'";
      if ( 
    $key != sizeof($array)-) {
        
    $jsonString.= ', ';
      }
    }
    $jsonString.= ' }';
    echo 
    $jsonString


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •