Php 在数组中搜索特定代码
我有一些从数据库中获取的“代码”,并在php的表中对它们进行排序。第一个数组中以数字1开头的所有代码,第二个数组中以2开头的所有代码。。到9点Php 在数组中搜索特定代码,php,arrays,Php,Arrays,我有一些从数据库中获取的“代码”,并在php的表中对它们进行排序。第一个数组中以数字1开头的所有代码,第二个数组中以2开头的所有代码。。到9点 Array ( [1] => Array ( [0] => 1264 [1] => 1264536 [2] => 1264537 [3] => 1264538 ) [2] => Array ( [0] => 213
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我是循环的初学者这可能是一个简单的方法:
$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...
}
我还为您重构了代码
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)
}
你们应该开始发布实际的数组,而不是数组结果。