php - Update minimum values based on another value - MySql -
i have set of information, i'm exploding id,code , number.
list ($id,$code,$num) = explode("~",$data);
i need update mysql based on unique code
minimum of num
for suppose first 3 requests looks like
id = 9267399 code = 5d:148 num = 64 id = 9267398 code = 5d:186 num = 71 id = 9267397 code = 5d:122 num = 93
then 4th,5th requests has duplicate code 5d:148
different id's , num's.
id = 9267402 code = 5d:148 num = 22 id = 9267563 code = 5d:148 num = 5
now need find min(num)
duplicate code
, update record mysql. queries should like
$sql = "update table set id = '9267398', num = '71' code = '5d:186' "; $sql = "update table set id = '9267397', num = '93' code = '5d:122' "; $sql = "update table set id = '9267563', num = '5' code = '5d:148' ";
here 5d:148
has 3 requests in min(num)
5.
i have tried finding duplicate code
$temp = array(); foreach ($code $c) { isset($temp[$c]) or $temp[$c] = 0; $temp[$c] ++; } var_dump($temp);
this giving me
array(3) {["5d:148"]=> int(3) ["5d:186"]=> int(1) ["5d:122"]=> int(1)}
i'm stuck here how find min(num)
, run update query based on it
looping through array , check if num lower previous one.
example of $data array:
$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 $val) { if(array_key_exists($val['code'], $array_to_add)) { if((int) $val['num'] < (int) $array_to_add[$val['code']]['num']) { // check if num lower previous 1 $array_to_add[$val['code']] = $val; // if yes, overwrite code key new values } } else { $array_to_add[$val['code']] = $val; // add values array if code doesn't exist in array_to_add } } var_dump($array_to_add); // array add in database foreach($array_to_add $val) { mysql_query("update table set id = ".mysql_real_escape_string($val['id']).", num = ".mysql_real_escape_string($val['num'])." code = '".mysql_real_escape_string($val['code'])."' "); } ?>
tip: @ pdo , mysqli better use of mysql query's.
Comments
Post a Comment