如何将项目添加到 json 文件格式化数组
Posted
技术标签:
【中文标题】如何将项目添加到 json 文件格式化数组【英文标题】:how to add item to the json file formatted array 【发布时间】:2013-04-17 12:50:48 【问题描述】:我只使用 1 个数据插入到我的 json 文件中。
$data=$_POST['myusernamer'];
$inp = file_get_contents('7players.json');
$tempArray = json_decode($inp);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents('7players.json', $jsonData);
这就是我的 json 文件的外观。我只想在最后添加 1 个玩家。
"players":[
"name":"Moldova",
"image":"/Images/Moldova.jpg",
"roll_over_image":"tank.jpg"
,
"name":"Georgia",
"image":"/Images/georgia.gif",
"roll_over_image":"tank.jpg"
,
"name":"Belarus",
"image":"/Images/Belarus.gif",
"roll_over_image":"tank.jpg"
,
"name":"Armenia",
"image":"/Images/armenia.png",
"roll_over_image":"tank.jpg"
,
"name":"Kazahstan",
"image":"/Images/kazahstan.gif",
"roll_over_image":"tank.jpg"
,
"name":"Russia",
"image":"/Images/russia.gif",
"roll_over_image":"tank.jpg"
,
],
"games" : [
"matches" : [
"player1id":"*",
"player2id":"*",
"winner":"*"
,
"player1id":"*",
"player2id":"*",
"winner":"*"
,
"player1id":"*",
"player2id":"*",
"winner":"*"
,
"player1id":"*",
"player2id":7,
"winner":"*"
,
"player1id":"*",
"player2id":"*",
"winner":"*"
,
"player1id":"*",
"player2id":"*",
"winner":"*"
,
"player1id":"*",
"player2id":"*",
"winner":"*"
]
,
"matches" : [
"player1id":"*",
"player2id":"*",
"winner":"*"
,
"player1id":"*",
"player2id":"*",
"winner":"*"
,
"player1id":"*",
"player2id":"*",
"winner":"*"
,
"player1id":"*",
"player2id":7,
"winner":"*"
,
"player1id":"*",
"player2id":"*",
"winner":"*"
,
"player1id":"*",
"player2id":"*",
"winner":"*"
,
"player1id":"*",
"player2id":"*",
"winner":"*"
,
]
]
我的问题是,如何在最后添加播放器?我也想知道如何更新
player1id":"*",
"player2id":"*",
"winner":"
在匹配数组中。
【问题讨论】:
【参考方案1】:只需解码您的 json 字符串,然后使用数组推送
$tempArray = json_decode($jsonstring, true);
array_push($tempArray, $your_data);
根据你的情况
$str = '
"players":[
"name":"Moldova",
"image":"/Images/Moldova.jpg",
"roll_over_image":"tank.jpg"
,
"name":"Georgia",
"image":"/Images/georgia.gif",
"roll_over_image":"tank.jpg"
]';
$arr = json_decode($str, true);
$arrne['name'] = "dsds";
array_push( $arr['players'], $arrne );
print_r($arr);
只检查 print_r($arr); 的值我希望这是你想要的。 :)
【讨论】:
这不会失败吗?我一直认为 json_decode 是对象表示而不是数组。您可以使用 true 作为第二个参数,以便获得关联数组表示?谢谢你的解释:) @intelis 说得好,第二个参数非常重要。 :) @chandresh_cool 非常感谢您的回复..我有疑问..我可以在一个 araay 中只传递 1 个值,只说玩家的名字,然后留下其余的..这会不会造成任何问题?? @chandresh_cool 如果你能帮我解决这个问题,请帮我..$inp = file_get_contents('7players.json'); $tempArray = json_decode($inp, true); $arrne['name'] = $_POST['myusernamer']; array_push($arr['players'], $arrne); $jsonData = json_encode($tempArray); $jsonData = json_encode($tempArray); file_put_contents('7players.json', $jsonData);它说第一个参数必须是数组..它们是数组..这里做错了什么? 将你的 array_push 行改为这个 array_push( $tempArray['players'], $arrne );【参考方案2】:添加其他玩家
$tempArray = json_decode($inp, true);
array_push($tempArray['players'], array('name' => $data['username'], 'image' => $data['userimage'], 'roll_over_image' => 'tank.jpg'));
更新匹配
第一个匹配数组
$tempArray['games'][0]['matches'];
第二个匹配数组
$tempArray['games'][1]['matches'];
现在是简单的二维数组,带有键 player1id
、player2id
和 winner
- 应该很容易更新这些。
之后,您可以将$tempArray
编码回 json。
【讨论】:
感谢回复!!如果某些值中没有值怎么办..我根本不通过..或者我用空值传递..然后会发生什么..【参考方案3】:<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js" ></script>
</head>
<body>
<?php
//first copy your json data data.json
$str = file_get_contents('data.json');//get contents of your json file and store it in a string,bro small suggestion never keep any JSON data in ur html file its not safe.always keep json data in external file.
$arr = json_decode($str, true);//decode it
$arrne['players'] = "sadaadad";
$arrne['image'] = "sadaadad";
$arrne['roll_over_image'] = "sadaadad";
array_push( $arr['employees'], $arrne);//push contents to ur decoded array i.e $arr
$str = json_encode($arr);
//now send evrything to ur data.json file using folowing code
if (json_decode($str) != null)
$file = fopen('data.json','w');
fwrite($file, $str);
fclose($file);
else
// invalid JSON, handle the error
?>
</body>
【讨论】:
【参考方案4】:在核心 PHP 中
如果你想要一个 JSON 响应数组。那么你可以使用这个代码。
很简单的方法,你可以使用这些步骤。
1) 步骤您必须使用 json_decode() 将 JSON 转换为数组。
2) 使用 array_merge() 方法添加新数组。如果你有兴趣添加一个数组。
$staff = json_decode($staffRes ,true);
$driver = ["helpers"=>[id=>1,name=>hep1],[id=>2,name=>hep2]]
$profile= array_merge($staff ,$driver );
在 Laravel 中
$staff = collect($staffRes)->toArray() ; // json() also work here.
$driver = ["helpers"=>[id=>1,name=>hep1],[id=>2,name=>hep2]]
$profile= array_merge($staff ,$driver );
输出
"error": 0,
"errmsg": "",
"response":
"id": "NlF4VDMrdEoxM2RCUWkxUE92c29tZz09",
"type": "DRIVER",
"driver_name": "Ravi Kumar",
"route_name": "Barasat Dak Bungalow",
"helpers": [
"helper_id": "K09NTlpHMStiNGlKSGZNMUIyWlAxZz09",
"helper_name": "Arvind Kumar",
"helper_mobile": "7777777775",
"helper_alt_mobile": "7777777777",
"birth_date": "01-10-2000",
"address": "Bongaon",
"id_proof": "123456789-WB",
"licence_no": null,
"experience": "2-year",
"helper_photo":""
,
"helper_id": "K29la21vY0VnMTZ5cFY2MU02cm1ZUT09",
"helper_name": "SUBIR DAS",
"helper_mobile": "5555555555",
"helper_alt_mobile": "5555555554",
"birth_date": "30-10-2019",
"address": "610/8, ....",
"id_proof": "NA",
"licence_no": "NA",
"experience": "2 years",
"helper_photo": ""
]
【讨论】:
【参考方案5】:使用这个 php 代码
<?php
$message = '';
$error = '';
if(isset($_POST["submit"]))
if(empty($_POST["title"]))
$error = "<label class='text-danger'>Enter details</label>";
else if(empty($_POST["image"]))
$error = "<label class='text-danger'>Enter Posted By</label>";
else
if(file_exists('myfile.json'))
$current_data = file_get_contents('myfile.json');
$array_data = json_decode($current_data, true);
$extra = array(
'title' => $_POST['title'],
'image' => $_POST["image"],
);
$array_data[] = $extra;
$products['products']=$array_data[];
$final_data = json_encode($products);
if(file_put_contents('myfile.json', $final_data))
$message = "<label class='text-success'>Added Successfully</p>";
else
$error = 'JSON File not exits';
?>
【讨论】:
以上是关于如何将项目添加到 json 文件格式化数组的主要内容,如果未能解决你的问题,请参考以下文章