<?php
b = [
['time' => 4, 'fruit' => 'banana_1', ],
['time' => 7, 'fruit' => 'banana_2', ],
['time' => 8, 'fruit' => 'banana_3', ],
['time' => 12, 'fruit' => 'banana_4', ],
['time' => 17, 'fruit' => 'banana_5', ],
['time' => 18, 'fruit' => 'banana_6', ],
['time' => 23, 'fruit' => 'banana_7', ],
['time' => 27, 'fruit' => 'banana_8', ],
];
time_line = [3,7,12,16,19,23,26];
/**
a,b,c為三框水果上架的時間和水果編號的集合辞做,time_line顧客進(jìn)店的時間點(diǎn)集合,
顧客會購買最近上架或等待購買即將上架的水果(若上架時間與進(jìn)店時間差和即將上架時間與進(jìn)店時間差相等,且已上架的水果未被購買則購買已上架的水果)礼饱,
每個時間點(diǎn)布疼,都會在3框水果去購買
請計算出每個進(jìn)店時間點(diǎn)顧客購買的水果有哪些燕锥。
例如前2個時間點(diǎn)購買的水果:[ 3=>['apple_1', 'banana_1', 'lemon_2', ], 7=>['apple_3', 'banana_2', 'lemon_4', ], ]
php版本語法兼容5.6
*/
//代碼寫在后面,寫完后赚楚,點(diǎn)擊左上角保存按鈕淌友,提示保存成功即可
function test(b, time_line){
arr_b = [];
result = [];
foreach($a as $val){
$arr_a[$val['time']] = $val['fruit'];
}
unset($val);
foreach($b as $val){
$arr_b[$val['time']] = $val['fruit'];
}
unset($val);
foreach($c as $val){
$arr_c[$val['time']] = $val['fruit'];
}
unset($val);
foreach($time_line as $val){
$res = [];
if($val == isset($arr_a[$val])){
$res[] = $arr_a[$val];
}else{
$res_val = common($val, $arr_a);
$res[] = $res_val;
unset($res_val);
}
unset($arr_a[$val]);
if($val == isset($arr_b[$val])){
$res[] = $arr_b[$val];
}else{
$res_val = common($val, $arr_b);
$res[] = $res_val;
unset($res_val);
}
unset($arr_b[$val]);
if($val == isset($arr_c[$val])){
$res[] = $arr_c[$val];
}else{
$res_val = common($val, $arr_c);
$res[] = $res_val;
unset($res_val);
}
unset($arr_c[$val]);
$result[$val] = $res;
}
return $result;
}
function common(arr){
// 把當(dāng)前val值push到key的數(shù)組中 重新排序 然后取出當(dāng)前val計算得出應(yīng)該取上還是下
arr);
array_push(val);
sort($arr_keys);
$search_key = array_search($val, $arr_keys);
if($search_key - 1 < 0){
$res_val = $arr[$arr_keys[$search_key+1]];
}else{
if(abs($arr_keys[$search_key] - $arr_keys[$search_key+1]) >= $arr_keys[$search_key] - $arr_keys[$search_key-1]){
$res_val = $arr[$arr_keys[$search_key-1]];
}else{
$res_val = $arr[$arr_keys[$search_key+1]];
}
}
return $res_val;
}