我有一组信息,我将其爆炸为id,代码和数字.
list ($id,$code,$num) = explode("~",$data);
假设我的前3个请求看起来像
id = 9267399
code = 5D:148
num = 64
id = 9267398
code = 5D:186
num = 71
id = 9267397
code = 5D:122
num = 93
然后我的第4,第5个请求有重复的代码5D:148,具有不同的id和num.
id = 9267402
code = 5D:148
num = 22
id = 9267563
code = 5D:148
num = 5
现在我需要找到重复代码的min(num)并将该记录更新回MysqL.我的查询应该是这样的
$sql = "UPDATE table SET id = '9267398',num = '71' WHERE code = '5D:186' ";
$sql = "UPDATE table SET id = '9267397',num = '93' WHERE code = '5D:122' ";
$sql = "UPDATE table SET id = '9267563',num = '5' WHERE code = '5D:148' ";
这里5D:148有3个请求,其中min(num)是5.
我试过找到重复的代码
$temp = array();
foreach ($code as $c) {
isset($temp[$c]) or $temp[$c] = 0;
$temp[$c] ++;
}
var_dump($temp);
这给了我
array(3) {["5D:148"]=> int(3) ["5D:186"]=> int(1) ["5D:122"]=> int(1)}
我被困在这里如何找到min(num)并根据它运行我的更新查询
最佳答案
循环遍历数组并检查num是否低于前一个数字.
$data数组的示例:
$data = array(
[0] => array('id' => 9267399,'code' => '5D:148','num' => 64),[1] => array('id' => 9267398,'code' => '5D:186','num' => 71)
);
–
PHP
$array_to_add = array();
foreach($data AS $val) {
if(array_key_exists($val['code'],$array_to_add)) {
if((int) $val['num'] < (int) $array_to_add[$val['code']]['num']) { // Check if num is lower than the prevIoUs one
$array_to_add[$val['code']] = $val; // If yes,overwrite code key with new values
}
} else {
$array_to_add[$val['code']] = $val; // Add values to array if code doesn't exist in array_to_add
}
}
var_dump($array_to_add); // ARRAY TO ADD IN DATABASE
foreach($array_to_add AS $val) {
MysqL_query("UPDATE table SET id = ".MysqL_real_escape_string($val['id']).",num = ".MysqL_real_escape_string($val['num'])." WHERE code = '".MysqL_real_escape_string($val['code'])."' ");
}
?>