Braydon Harris Braydon Harris - 11 days ago 8
PHP Question

PHP json array to delete a line in JSON file

Having a bit of an issue with some PHP code. I have an contacts list angular app to add and remove contacts. I have the add part done but the delete is giving me some grief. On ng-click I'm sending data with a $http request to remove a specific line in a JSON file. It's sending the data fine but I think something is wrong with my php...

delete.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);


app.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)">


Any help would be greatly appreciated

Answer

Because json_decode is being called with assc==true the returning array is associative, and you should use $value['number'] instead of $value->number

An corrected code with the array_filter function for brevity:

//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);