0

recently im trying to work with JSON data via php for my higher education project. But I hanged-up while managing/updating this into the JSON file.

Let me introduce you the whole scenario:

Its a entry based project, where all entries must be save in the JSON file (.json), format is :

[{"Name":"xyz","UID":"1234","RDate":"11122014","ReLogin":"true","LTime":"1e3","Passive":"false"},{"Name":"abc","UID":"5678","RDate":"01102014","ReLogin":"true","LTime":"1e3","Passive":"false"},......]

Now, what I have to do is that: when a new entry sended to the PHP, than firstly find the match entry based on some paremater, like name, uid, rdate. IF MATCH FOUND, than replace/update the whole entry into the file, IF MATCH NOT FOUND, than add/write the new entry into the file.

To do this, currently I'm trying to use these bunch of codes:

1) `function chkEntry($uid,$entry)

$file='file.json';
$s[]=$entry;$match=0;
global $RESP;
if(0==filesize($file)){
  return true;
}else{
  $data=json_decode(file_get_contents($file),true);
  foreach($data as $keyD=>$valD){
    foreach($s as $keyS=>$valS){
      if($valD["Name"]!=$valS["Name"]||$valD["UID"]!=$valS["UID"]||$valD["RDate"]!=$valS["RDate"]){ // here `RDate` is always unique, so I can use it for the matching process
        $match=0;
      }else{
        $match=1;
      }
    }
  }
  if($match==1){return false;}else{return true;}
}

This chkEntry always return false :( And also I don't know that how to replace the while entry int the file, if match found.

UPDATED chkEntry function: matching criteria is limited to a single parameter only [uid]. If match found, than delete the whole entry and return true to the addEntry function, so that addEntry add the new entry.But unfortunately this function is also not working as expected.

function chkEntry($uid,$entry){
  $file='file.json';
  $data=json_decode(file_get_contents($file),true);
  foreach($data as $keyD=>$valD){
    if($valD["uid"]==$entry["uid"]){
      unset($data[$keyD]); //delete the entry, if matched
      file_put_contents($file,json_encode($data));
      return true;
    }
  }
  return true;
}

2) `function addEntry($uid,$entry)

global $RESP;
$ready=false;
$file='file.json';
if(addFile($uid)){ //`function addFile`, if file not exists, than create an blank file
  $data=json_decode('file.json',true);
  unset($file);
  if(chkEntry($uid,$entry)){ //`function chkEntry`, match the entry
    $data[]=$entry;
    file_put_contents('file.json',json_encode($data)); 
    unset($data);
  }else{
    $RESP["entry"]="This entry is already exists into Database";
  }
  $ready=true;
}else{
  $RESP["err"]="We are unable to add the entry right now. Please try after some time!";
}
if($ready){
  if(!isset($RESP["entry"])){$RESP["entry"]="for evaluatuion";}
  return true;
}else{
  $RESP["err"]="Something went wrong! Please try to add this later.";
  return false;
}

3)

$entry=array("Name"=>$_POST["name"],"UID"=>$_POST["uid"],"RDate"=>$_POST["rdate"],"ReLogin"=>$_POST["relogin"],"LTime"=>$_POST["ltime"],"Passive"=>$_POST["passive"]);
addServer($uid,$entry);

So, my question is :

How the finding/matching function should be managed, so that its return true if match found otherwise return false and IF MATCH FOUND, than how to replace/update the whole entry into the file.

for example: if the new entry is

{"Name":"try","UID":"1111","RDate":"12122014","ReLogin":"`true","LTime":"1e3","Passive":"false"}

than first match it to the existing entries and than ad it to the file.

IF the new entry is : (based on name, uid, rdate)

{"Name":"xyz","UID":"2222","RDate":"15122014","ReLogin":"true","LTime":"1e3","Passive":"false"} //match found, based on `name`

OR

{"Name":"nws","UID":"1234","RDate":"19122014","ReLogin":"true","LTime":"1e3","Passive":"false"} //match found, based on `uid`

OR

{"Name":"nws","UID":"2222","RDate":"11122014","ReLogin":"true","LTime":"1e3","Passive":"false"} //match found, based on `rdate`

than update/replace the old entry {"Name":"xyz","UID":"1234","RDate":"11122014","ReLogin":"true","LTime":"1e3","Passive":"false"} with it.

help me plz.....

Thanks & Regards

2 Answers 2

1

Here's how I would go about doing it (minus the error messages) simplifying everything down to one function.

define('JSON_FILE', 'file.json');

function addEntry($newEntry)
{
    // flag to indicate whether an update was made or not;
    // flag is by default set to false to assume no update was made
    $update = false; 
    // retrieve list of current entries
    if (file_exists(JSON_FILE)) {
        $entries = json_decode(file_get_contents(JSON_FILE), true);
    }
    // if there are entries, look for a match 
    if (!empty($entries)) {
        foreach ($entries as $i => $entry) {
            // if match IS found...
            if ($entry["Name"] == $newEntry["Name"] || 
                $entry["UID"] == $newEntry["UID"] || 
                $entry["RDate"] == $newEntry["RDate"]){
                // update/replace existing entry with new entry
                $entries[$i] = $newEntry;
                // turn on flag to indicate that an update was made
                $update = true;
                // no need to keep searching any further, so quit loop
                break;
            }
        }
    // otherwise if there no entries, create an empty list
    } else {
        $entries = array();
    }
    // if no update was made i.e. no match was found, then it means a new entry needs to be added
    if (!$update) {
        // add new entry
        $entries[] = $newEntry;
    }
    // save list of entries 
    file_put_contents(JSON_FILE, json_encode($entries));
}

$entry = array(
     "Name" => $_POST["name"],
     "UID" => $_POST["uid"],
     "RDate" => $_POST["rdate"],
     "ReLogin" => $_POST["relogin"],
     "LTime" => $_POST["ltime"],
     "Passive" => $_POST["passive"]
);

addEntry($entry);
Sign up to request clarification or add additional context in comments.

9 Comments

I want to know one more thing (its not a part of that question). If somebody enter a value of the entry for retrieving the whole entry, than how can we match and retrieve it unless we don't know that the supplied parameter is name OR uid or the rdate? And same thing happens when he want to delete the entry based on the supplied paramter...
I'm sorry. I don't quite understand what you just asked. What do you mean by "how can we match and retrieve it unless we don't know that the supplied parameter is name OR uid OR rdata"?
I mean to say that, If I want a specific entry details via the supplied parameter (means supplied parameter can be name OR uid OR rdata), than how can I match the parameter with the $entry["name"] OR $entry["uid"] OR $entry["rdate"]
For example (take a look of the JSON format from the question): I want to get the details of uid=1234 and send it to the responsible function as getEntry($param);. So how can I configure the getEntry function so that it can match $param with uid & name & rdate, and the send back the whole matched entry. And same process should happen while removing an entry with removeEntry function.
You would change the foreach's if condition to $entry["name"] == $supplied_param || $entry["uid"] == $supplied_param || $entry["rdate"] == $supplied_param
|
0

chkEntry is probably failing because json_decode() errors out. Json_decode returns null on error, and in php $x = null; $x[1] === NULL is always true; all subscripted values on a null $x will be null and thus equal to each other.

Comments

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.