我有一些"代码"我从数据库中获取并在php中的表中对它们进行排序。所有代码以第一个数组中的数字1开头,所有代码以第二个中的2开头直到9。
Array
(
[1] => Array
(
[0] => 1264
[1] => 1264536
[2] => 1264537
[3] => 1264538
)
[2] => Array
(
[0] => 213
[1] => 21320
[2] => 21321
[3] => 21322
)...
代码
function getCodes($codeEgr){
$oneTable = array();
$twoTable = array();
$threeTable = array();
$fourTable = array();
$fiveTable = array();
$sixTable = array();
$sevenTable = array();
$eightTable = array();
$nineTable = array();
foreach($codeEgr as $row)
{
list($destination,$codeTegr,$price,$effectiveDate) = $row;
$code = $codeTegr;
$first = substr($code,0,1);
switch($first)
{
case 1:
$oneTable[] = $code;
break;
case 2:
$twoTable[] = $code;
break;
case 3:
$threeTable[] = $code;
break;
case 4:
$fourTable[] = $code;
break;
case 5:
$fiveTable[] = $code;
break;
case 6:
$sixTable[] = $code;
break;
case 7:
$sevenTable[] = $code;
break;
case 8:
$eightTable[] = $code;
break;
case 9:
$nineTable[] = $code;
break;
}
}
$codeTable = array(1 => $oneTable,2 => $twoTable,3 => $threeTable,4 => $fourTable,5 => $fiveTable,
6 => $sixTable,7 => $sevenTable,8 => $eightTable,9 => $nineTable);
return $codeTable;
}
我想知道的是在这个数组中找到一个代码()。例如,如果我有像156545这样的代码,我只搜索第一个数组中的代码而不搜索其他代码。如果我有像265456这样的代码我在第二个数组中搜索... 返回true或false后如果发现或不是
我不知道怎么做php我是循环的初学者
答案 0 :(得分:2)
这可能是一个简单的方法:
$code= 123123;
$first = substr($code,0,1);
switch($first)
{
case 1:
$key = array_search($code, $oneTable);
break;
case 2:
$key = array_search($code, $twoTable);
break;
and so on...
}
答案 1 :(得分:0)
我也为你重构了代码
function getCodes($codeEgr){
$codes = array();
foreach($codeEgr as $row)
{
list($destination,$codeTegr,$price,$effectiveDate) = $row;
$code = $codeTegr;
$first = $code[0]; // get first digit of code string
$codes[$first][] = $code;
}
return $codes;
}
function searchCode($codesArr, $code){
$firstDigit = $code[0];
$searchIn = (isset($codesArr[$firstDigit])) ? $codesArr[$firstDigit] : array();
return array_search($code, $searchIn)
}