有些 PHP 代码有点问题。我有一个联系人列表 Angular 应用程序来添加和删除联系人。我已经完成了添加部分,但删除部分让我有些悲伤。在 ng-click 上,我使用 $http 请求发送数据以删除 JSON 文件中的特定行。它发送数据正常,但我认为我的 php 有问题...
删除.php
$jsonString = file_get_contents("contacts.json");
$contactData = json_decode($jsonString, true);
$getArray = array(
"firstname" => $_POST['firstname'],
"lastname" => $_POST['lastname'],
"number" => $_POST['number'],
"hobbies" => $_POST['hobbies']
);
foreach ($contactData as $key => $value) {
if($value->number == $getArray) {
unset($contactData[$key]);
}
}
$json = json_encode($contactData, JSON_PRETTY_PRINT);
//Add to JSON contents
file_put_contents("contacts.json", $json);
应用程序.js
$scope.deleteRow = function(contact){
console.log(contact);
//var index = $scope.number.indexOf(item);
$http({
method : 'POST',
url : 'delete.php',
data : $.param(contact),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data){
updateService.listWasUpdated();
});
};
html
<button type="button" class="btn btn-default" aria-label="Bold" ng-click="deleteRow(contact)">
任何帮助将不胜感激
最佳答案
因为 json_decode使用 assc==true
调用返回数组是关联的,您应该使用 $value['number']
而不是 $value->number
这是一个带有 array_filter 的更正版本为简洁起见的功能:
//load
$jsonString = file_get_contents("contacts.json");
$contactData = json_decode($jsonString, true);
//filter
$contactData = array_filter($contactData, function ($v) {return $v['number']!=$_POST['number'];});
//save
$json = json_encode($contactData, JSON_PRETTY_PRINT);
file_put_contents("contacts.json", $json);
关于javascript - PHP json数组删除JSON文件中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40821183/