Advanced Search

Results 1 to 3 of 3

Thread: array jSon

  1. #1
    Join Date
    Jan 2008
    Posts
    441
    Thanks
    67
    Thanked 4 Times in 4 Posts

    Default array jSon

    i have a text box with submit button that adds an item to the end of a list using jSon.
    Code:
    $commentsFile = 'data/comments.txt';
    $commentsText = file_get_contents($commentsFile);
    $commentsList = json_decode($commentsText,true);
    
    // this code "push" items to the end of jSon array
    $commentsList['comments'][] = array( 
    	'index' => $ind++,
    	'text' => $sComment,
    	'ip' => $serverIP
    );
    $commentsText = json_encode($commentsList); 
    file_put_contents($commentsFile, $commentsText);
    
    //desired output
    json file
    {"comments":[
    	{"index":3,"text":"item_3","ip":"127.0.0.1"},
    	{"index":1,"text":"item_1","ip":"127.0.0.1"},
    	{"index":2,"text":"item_2","ip":"127.0.0.1"}
    ]}

    everything works well but it pushes the item to the end of the list. is there a way to "unshift" and prepend a new item to the top of the list like the desired example above?
    Last edited by ggalan; 07-26-2011 at 02:37 AM.

  2. #2
    Join Date
    Jan 2008
    Posts
    441
    Thanks
    67
    Thanked 4 Times in 4 Posts

    Default

    i've tried this, but it just replaces the top item
    Code:
    $commentsList['comments'][0] = array( 
    	'index' => $ind++,
    	'text' => $sComment,
    	'ip' => $serverIP
    );

  3. #3
    Join Date
    Apr 2008
    Location
    So.Cal
    Posts
    3,623
    Thanks
    63
    Thanked 516 Times in 502 Posts
    Blog Entries
    5

    Default

    Quote Originally Posted by ggalan View Post
    ... is there a way to "unshift" and prepend a new item to the top of the list like the desired example above?
    yeah, and you named it - array_unshift()

    PHP Code:
    $commentsFile 'data/comments.txt';
    $commentsText file_get_contents($commentsFile);
    $commentsList json_decode($commentsText,true);

    $newentry = array(
        
    'index' => $ind++,
        
    'text' => $sComment,
        
    'ip' => $serverIP
    );

    array_unshift($commentsList['comments'], $newentry);

    $commentsText json_encode($commentsList); 
    file_put_contents($commentsFile$commentsText); 
    We Only Torture the Folks We Don't Like (You're Probably Gonna Be Okay)
    It's a Party in the CIA

  4. The Following User Says Thank You to traq For This Useful Post:

    ggalan (07-26-2011)

Bookmarks

Posting Permissions

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