2013-11-22 69 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; 
    } 
}