后端代碼規(guī)范避免數(shù)組下標越界
拋出問題
數(shù)組下標越界真的是開發(fā)過程中的痛,除了在開發(fā)過程中各種判斷是否設置,是否為空,還有其他優(yōu)雅的辦法解決嗎?
回答問題
肯定是有的
舉個栗子
比如,我有一個工具性質(zhì)的方法如下:
我怎么保證 $batchUserCover[$userid]['pickedFootprint'] 和 $batchFootprintList[$userid]['list'] 不會有下標越界的問題呢?
//批量獲得圖片故事 優(yōu)先精選故事 不足三個拼接最近發(fā)布的故事
public static function batchImageFootprint($userIds, $batchUserCover, $batchFootprintList)
{
$ret = [];
foreach ($userIds as $userid) {
$ret[$userid] = array_slice(array_merge($batchUserCover[$userid]['pickedFootprint'], array_slice($batchFootprintList[$userid]['list'], 0, 3)), 0, 3);
}
return $ret;
}
解題思路
1.在方法外判斷是否設置值
2.在方法外保證已經(jīng)設置值,確保 $batchUserCover[$userid]['pickedFootprint'] 這類參數(shù)一定是存在的,已經(jīng)設置了的.
我認為思路2更好
解題實踐
實踐1:
在傳入數(shù)據(jù)之前,設置好傳入值,保證傳入值的key必須存在,值可以為null,或者空數(shù)組。 核心代碼如下:
public static function batchFormatCoverAndPickedFootprint($userListInfo)
{
foreach ($userListInfo as &$element) {
$retData[$element['userid']] = [
'pickedFootprint' => [],
'coverFootprint' => [],
];
}
.
.
.
return $retData;
}
傳入的數(shù)組的key必然符合[$userid]['pickedFootprint'],不會存在數(shù)組下標越界
$batchUserCover = batchFormatCoverAndPickedFootprint(xxx);
self::batchImageFootprint($userIds, $batchUserCover);
實踐2:
和實踐1的底層思路是一致的,區(qū)別在于實踐1是在函數(shù)內(nèi)首先定義了符合規(guī)范的初始值
實踐2是先處理業(yè)務邏輯,在return之前定義了符合規(guī)范的初始值
(下面代碼段寫了注釋,重點看后半部分;聯(lián)合查詢那部分代碼質(zhì)量也不錯,沒省略掉,看能不能拋轉(zhuǎn)引玉。)
public static function batchFootprintList($userIds, $pageCount = 21, $batchPickedFootprints = [], $select = 'userid,id,mid,image,text,ST_Astext(picgeom) as "picgeom",poi,poiid,city,province,country,pictime')
{
.
.
.
//聯(lián)合查詢
$union = self::query()->selectRaw($select)->where('userid', $userIds[0])
->where('status', self::TYPE_STATUS_NORMAL)
->whereNotIn('mid', $batchPickedFootprints[$userIds[0]])
->orderBy('id', 'desc')
->limit($pageCount);
//避免重復查詢第一條數(shù)據(jù)
unset($userIds[0]);
foreach ($userIds as $userId) {
$unionItem = self::query()->selectRaw($select)->where('userid', $userId)
->where('status', self::TYPE_STATUS_NORMAL)
->whereNotIn('mid', $batchPickedFootprints[$userId])
->orderBy('id', 'desc')
->limit($pageCount);
$union->unionAll($unionItem);
}
$allUserFootprints = $union->get()->toArray();
$res = [];
$chunkFootprintByUserid = self::_chunkFootprintByUserid($allUserFootprints);
// 重點在這里
foreach ($allUserIds as $userId) {
$list = $chunkFootprintByUserid[$userId] ?? [];
$count = count($list);
//以此保證不會出現(xiàn)數(shù)據(jù)下標越界的問題
$res[$userId]['list'] = $list;
$res[$userId]['more'] = $count < $pageCount ? 0 : 1;
$res[$userId]['track'] = $count > 0 ? (string)$list[$count - 1]['id'] : '';
}
return $res;
}
注意
為了行文緊湊,代碼段中省略了和文章無關(guān)的代碼,用豎著的三個.省略。
以上就是后端代碼規(guī)范避免數(shù)組下標越界的詳細內(nèi)容,更多關(guān)于數(shù)組下標越界的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
javascript避免數(shù)字計算精度誤差的方法詳解
本篇文章主要是對javascript避免數(shù)字計算精度誤差的方法進行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助2014-03-03
在網(wǎng)頁里看flash的trace數(shù)據(jù)的js類
我的js類jdhcn.js中的一個flashDebug方法2009-01-01

