Reputation: 57
$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.
Upvotes: 0
Views: 78
Reputation: 19780
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]
.
Upvotes: 1