2013-11-22 67 views
0

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

$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'))); 

我试图更新failed-attempts的值,并添加一个newip地址给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[] 

    } 
} 

如何更新现有的阵列?

回答

1

这样的事情应该工作:

foreach($data as $key => $d){ 
    if (array_key_exists($username, $d)) { 
     $data[$key][$username]['ip'] = array("your_ip_value"); 
    } else { 
     ... 
    } 
} 
1
<?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; 
    } 
}