dongxi1965 2018-03-26 22:18
浏览 54

JSON对象上的array_unique

$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.

  • 写回答

1条回答 默认 最新

  • duanoucuo7045 2018-03-26 22:42
    关注

    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].

    评论

报告相同问题?

悬赏问题

  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单