0
$accountData                    = json_decode(file_get_contents($filetxt_1), true);
$newdata['id']                  = $uvon;
$newdata['wallet_address']      = $walletaddress;
$newdata['timestamp']           = time();
$accountData[]         = $newdata;
$array = array_values(array_unique( $accountData, SORT_REGULAR));
file_put_contents($filetxt_1, json_encode($array, JSON_PRETTY_PRINT));

Every time this PHP script is triggered by a $_POST, it is supposed to add a new JSON object to a file on the server. This works fine, except I need those objects to remain unique. I am attempting to achieve this with the array_unique and array_values functions.

After entering two sets of data containing a matching value, the output is this:

[
  {
      "id": "111.222.333.44",
      "wallet_address": "0x34c957891d19c88bc11e56c4ad6b1a65f09fda92",
      "timestamp": 1522101535
  },
  {
      "id": "111.222.333.44",
      "wallet_address": "0x3b958949efcc8362dd05179cce8eb5e16befebda",
      "timestamp": 1522101581
  }
]

The id's match, so the second object is not supposed to be in the file. Only if the id,wallet_address, and timecode are unique should the data be appended to the file.

2
  • checking only if the id exist can solve your issue or do you have to check also wallet_address? Commented Mar 26, 2018 at 22:26
  • Both wallet address and ID have to remain unique for this application. Commented Mar 26, 2018 at 22:40

1 Answer 1

1

You could check if the $uvon is already present in the id values by getting all id values (using array_column()), and check if the value is present or not, before to update the JSON file (and the same for wallet_address):

$accountData = json_decode(file_get_contents($filetxt_1), true);
$ids = array_column($accountData, 'id');
$was = array_column($accountData, 'wallet_address');
if (!in_array($uvon, $ids) && !in_array($walletaddress, $was)) {
    $newdata['id']                  = $uvon;
    $newdata['wallet_address']      = $walletaddress;
    $newdata['timestamp']           = time();
    $accountData[]         = $newdata;
    file_put_contents($filetxt_1, json_encode($accountData, JSON_PRETTY_PRINT));
}

The function array_unique() can only reduce an array of "not-complex" values. Ex:

$array = [2,3,4,5,5,5,6,"foo","bar","foo"];
$array = array_unique($array); 

Then $array will contains [2,3,4,5,6,"foo","bar].

Sign up to request clarification or add additional context in comments.

1 Comment

@CharlesRaiser You're welcome :) Don't forget to close your question if an answer solves your problem. Thanks :) See: meta.stackexchange.com/questions/5234/…

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.