Q:

Update minimum values based on another value - MySql

I have a set of information, which i'm exploding it to id,code and number.
list ($id,$code,$num) = explode("~",$data);

I need to update it to MySql based on unique code with minimum of num
For suppose my 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 my 4th,5th requests has duplicate code 5D:148 with different id's and num's.
id = 9267402
code = 5D:148
num = 22

id = 9267563
code = 5D:148
num = 5

Now i need to find min(num) for duplicate code and update that record back to mysql. My queries should look like
$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' ";

here 5D:148 has 3 requests in which min(num) is 5.
I have tried finding the duplicate code
$temp = array();
foreach ($code as $c) {
    isset($temp[$c]) or $temp[$c] = 0;
    $temp[$c] ++;
}
var_dump($temp); 

This is giving me
array(3) {["5D:148"]=> int(3) ["5D:186"]=> int(1) ["5D:122"]=> int(1)}  

I'm stuck here how do i find min(num) and run my update query based on it

A:

Looping through the array and check if num is lower then the 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 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'])."' ");

}

?>

Tip: Look at PDO and mysqli for better use of mysql query's.

