添加到json对象顺序


Add to json object order

有没有一种方法可以在开头而不是结尾写入json对象?当我现在加的时候,它会把它放在底部。我需要它在顶部,因为最新的数据才刚刚开始。

<?php
    $file = file_get_contents('./data.json');
    $data = json_decode($file);
    unset($file);
    $data[] = array('data'=>'some data');
    file_put_contents('data.json',json_encode($data));
    unset($data);

在上面这个简单的例子中,就像@jeroen在评论中所说的那样,您可以使用array_unshift()来实现这个目的:

假设最初我们有data.json,内容如下:

[{"data":"somedata 1"},{"data":"somedata 2"},{"data":"somedata 3"}]

你想在它前面加上值。

$file = file_get_contents('data.json'); // get the file
$data = json_decode($file, true); // turn it into an array (true flag)
unset($file);
// $data[] = array('data'=>'some data');
// Don't use this, this will append/push the data in the end
array_unshift($data, array('data' => 'some data 4')); // unshift it
file_put_contents('data.json',json_encode($data)); // put it back together again
unset($data);

最后,你会得到这样的东西:

[{"data":"some data 4"},{"data":"somedata 1"},{"data":"somedata 2"},{"data":"somedata 3"}]

注意:如果您拥有正确的权限