merge array quantity php
this is my working code:
while ($list = mysql_fetch_assoc($result)) {
$sql2开发者_JAVA百科 = "SELECT * FROM stock WHERE gID=".$list['gID'];
$result2 = mysql_query($sql2, $conn) or trigger_error("SQL", E_USER_ERROR);
$totalgid = mysql_num_rows($result2);
$sql3 = "SELECT * FROM stockcount WHERE gID=".$list['gID']." AND date='".$list['date']."' AND affectstock=1";
$result3 = mysql_query($sql3, $conn) or trigger_error("SQL", E_USER_ERROR);
$dategid = mysql_num_rows($result3);
$calculategid = $totalgid - $dategid;
if ($calculategid < 0) {
if(isset($arr[$list['date']][$list['gID']])){
//increment
} else {
//set to initial value of 1
$arr[$list['date']][$list['gID']]=$calculategid;
}
}
}
print_r($arr);
do you have a loop outside this that is something like foreach($someList as $list){ ...do this code... }
? I only ask because you should never have duplicate values because if you try to set a value into the same exact key, will overwrite the previous value. I can only assume based on the code you posted that you are appending this array to another array inside a loop. If that is the case, something like this might help:
//initialize the output array
$arr = array();
//loop through somelist
foreach($someList as $list){
//check if the key exists, if so increment.
if(isset($arr[$list['date']][$list['gID']])){
//increment
$arr[$list['date']][$list['gID']]++;
} else {
//set to initial value of 1
$arr[$list['date']][$list['gID']]=1;
}
}
print_r($arr);
essentially, just check if the key isset()
and if so, increment, if not set to 1.
精彩评论