Php 更新数组的值

Php 更新数组的值,php,Php,我试图逐行读取文件并将值存储到数组中。如果用户名已经存在于数组中,则更新用户名的现有数组,如果不存在,则创建新数组 $data[] = array('username1'=>array('failed-attempts'=>'0','ip'=>array('191.25.25.214'))); $data[] = array('username2'=>array('failed-attempts'=>'0','ip'=>array('221.25.25.2

我试图逐行读取文件并将值存储到数组中。如果用户名已经存在于数组中,则更新用户名的现有数组,如果不存在,则创建新数组

$data[] = array('username1'=>array('failed-attempts'=>'0','ip'=>array('191.25.25.214'))); 

$data[] = array('username2'=>array('failed-attempts'=>'0','ip'=>array('221.25.25.214')));  
我正在尝试更新失败的尝试值,并在用户名数组存在时向ip数组添加新的ip地址

我试过这个

foreach($data as $d){
    if (array_key_exists($username, $d)) {
           //username is already in the array, update attempts and add this new IP.


    }else{

        $data[] = array('username3'=>array('failed-attempts'=>'0','ip'=>array('129.25.25.214')));  //username is new, so add a new array to $data[]

    }
}

如何更新现有阵列?

类似的操作应该可以:

foreach($data as $key => $d){
    if (array_key_exists($username, $d)) {
        $data[$key][$username]['ip'] = array("your_ip_value");
    } else {
        ...
    }
}

<?php

$result = array();
foreach($data as $d){

    $ip = ''; // get the ip, maybe from $d?
    $username = ''; // get the username

    // if exist, update
    if (isset($result[$username])) {
        $info = $result[$username];
        $info['failed-attempts'] += 1;
        $info['ip'][] = $ip;

        $result[$username] = $info;
    } else {
        $info = array();
        $info['failed-attempts'] = 0;
        $info['ip'] = array($ip);
        $result[$username] = $info;
    }
}