2017-10-16 98 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允許你創建一個匿名對象