Log in

View Full Version : Resolved array jSon



ggalan
07-25-2011, 08:14 PM
i have a text box with submit button that adds an item to the end of a list using jSon.


$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?

ggalan
07-25-2011, 08:16 PM
i've tried this, but it just replaces the top item


$commentsList['comments'][0] = array(
'index' => $ind++,
'text' => $sComment,
'ip' => $serverIP
);

traq
07-26-2011, 02:30 AM
... 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() :D



$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);