我正在尝试逐行读取文件并将值存储到数组中。如果已经在数组中的用户名更新用户名的现有数组,如果没有创建新数组。
$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数组。
我试过这个
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[]
}
}
如何更新现有阵列?
答案 0 :(得分:1)
这样的事情应该有效:
foreach($data as $key => $d){
if (array_key_exists($username, $d)) {
$data[$key][$username]['ip'] = array("your_ip_value");
} else {
...
}
}
答案 1 :(得分: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;
}
}