1

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

2 Answers 2

1

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

Here is a corrected version 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);
Sign up to request clarification or add additional context in comments.

Comments

1

The issue is that you are not specifying the number key under the $getArray in the If statement, it needs to be replace with $getArray['number'].

if($value->number == $getArray['number']) {
    unset($contactData[$key]);
}

Is there a reason you are not using SQLite to store your contact info? It would make it a lot easier to handle storing and manipulating of your contacts.

2 Comments

voting up for the suggestion to use a SQLite
Yeah I know a database is the correct way to go, but this is just a learning app for angular and only working with like 10 lines of JSON.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.