2017-10-16 133 views
0

我正在玩JSON。假设我的users.json中有这样的数据:将数据输入到JSON到数组中的对象

{ 
    "users": 
    [ 
     { 
      "id": "1", 
      "name": "Aegon Targaryen", 
      "activation_key" :"18494810491048adcf" 
     }, 

     { 
      "id": "2", 
      "name": "Jamie Lanister", 
      "activation_key" : "756883" 
     }, 

     { 
      "id": "3", 
      "name": "Brandon Stark", 
      "activation_key" : "12984819849r94fr2" 
     } 
    ] 
} 

如何计算这个“users”数组中有多少个对象?我想输入另一个对象,如

{ 
    "id": "4", 
    "name": "Arya Stark", 
    "activation_key" : "2471984919edr2" 
} 

之后的最后一个对象,但我还没有找到办法做到这一点。

+0

http://php.net/manual/en/function.array-push.php – timakro

+0

'users.length',“users.push(新OBJ数据)'?什么语言? – kris

回答

0

您可以用count计算用户的数量,并在与[] =array_push

$file = 'users.json'; 
$data = json_decode(file_get_contents($file), true); 
// count users 
$countOfUsers = count($data['users']); 
// add an new user 
$data['users'][] = [ 
    'id' => $countOfUsers + 1, 
    'name' => 'some name', 
    'activation_key' => 'some key' 
]; 
// write back 
file_put_contents($file, json_encode($data)); 
2

阵列时,您可以简单地用count()

$youJson = file_get_contents('Path'); 


$data = json_decode($yourJson,true); 

现在你可以做到这一点的推送数据简单地得到用户count($data['users'])

希望这有助于。

0

使用json_decode

像:

$data = json_decode(file_get_contents('path/to/json_file')); 

然后

$users = count($data->users); 

echo $users; 

希望这有助于。

0

假设你已经读过您JSON文件由

$json_array = json_decode($json); 

2到PHP为$ JSON

1)转让$ JSON字符串数组)计数的用户

$user_count = count($json_array->user); 

3 )添加新用户

3.1创建新的使用对象

$new_user = array() 
$new_user["id"] = "4"; 
$new_user["name"] = "Arya Stark"; 
$new_user["activation_key"] = "2471984919edr2”; 

3.2推用户对象

$json_array->user[] = $new_user; 
1
$b=json_decode(file_get_contents('users.json'), true); 


echo " total number of objects = ".count($b->users); 
//var_dump($b); // you can see details of $b from here 

// Append the new object to users array 
$new_obj=new Stdclass(); 
$new_obj->id="4"; 
$new_obj->name="Arya Stark"; 
$new_obj->activation_key="2471984919edr2"; 

$b->users[]=$new_obj; 

//var_dump($b); // you can see that the new object is added here 

取消对var_dump线看到$b的完整结构。

BTW Stdclass允许你创建一个匿名对象