我需要创建带有运营商名称和绑定到它们的ID的数组。然后我想执行一些像int A[] = new int[5];
int B[] = new int[5];
int C[] = new int[5];
C[0] = 1;
for (int i = 0; i <= 4; i++) {
if (B[i] < C[i]) {
A[i] = C[i] - 1;
}
else {
A[i] = B[i] + 1;
C[i] = B[i] + 3;
B[i] = B[i] | C[i] - 1;
}
}
这样会返回运营商名称的内容。
get_carrier_name_by_id(id)
这是保存数据的正确方法吗?
答案 0 :(得分:1)
试试这个:
function get_carrier_name_by_id($id)
{
$carriers = array (
"DPD" => array(1,2,3),
"DPD Pobranie" => array(4,5,6),
"Poczta-Polska" => array(7,8,9),
"Poczta-Polska pobranie" => array(10,11,12),
"Paczkomat" => array(13,14,15),
"Paczkomat pobranie" => array(16,17,18),
"Osobisty" => array(19,20,21),
"UPS" => array(22,23,24),
"UPS pobranie" => array(25,26,27)
);
foreach($carriers as $name => $ids)
if(in_array($id, $ids))
return $name;
return null;
}
echo '<pre>';
var_dump(get_carrier_name_by_id(122));
var_dump(get_carrier_name_by_id(12));
var_dump
s的输出:
NULL
string(22) "Poczta-Polska pobranie"
答案 1 :(得分:1)
使用迭代器查看下面的解决方案:
function get_carrier_name_by_id($id)
{
$carriers = array(
"DPD" => array(1, 2, 3),
"DPD Pobranie" => array(4, 5, 6),
"Poczta-Polska" => array(7, 8, 9),
"Poczta-Polska pobranie" => array(10, 11, 12),
"Paczkomat" => array(13, 14, 15),
"Paczkomat pobranie" => array(16, 17, 18),
"Osobisty" => array(19, 20, 21),
"UPS" => array(22, 23, 24),
"UPS pobranie" => array(25, 26, 27)
);
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($carriers));
foreach ($it as $key => $val) {
$key = $it->getSubIterator($it->getDepth() - 1)->key();
if($val == $id){
return $key;
}
}
}
echo get_carrier_name_by_id(3); //Output: DPD
echo get_carrier_name_by_id(12); //Output: Poczta-Polska pobranie
echo get_carrier_name_by_id(24); //Output: UPS
答案 2 :(得分:1)
您可以使用array_filter()
,in_array()
和key()
轻松获取运营商名称:
$key = 4;
$carrier = key( array_filter( $carriers, function( $row ) use( $key ) { return in_array( $key, $row ); } ) );
echo $carrier;
将输出:
DPD Pobranie
基本上,您必须将$carriers
数组过滤为匹配的$key
。您可以array_filter
使用anonymous function:array_filter
将每个数组元素传递给被调用函数,如果函数返回可评估为True的值,则在过滤后的数组中返回该元素,否则它被丢弃了。在您的情况下,我们检查元素项中是否有请求的密钥。
然后,我们使用key()
返回已过滤数组的当前指向元素的键:刚创建数组,因此指针位于数组的开头。
如果需要,您可以将此脚本调整为函数:
function CarrierByID( $carriers, $key )
{
return key( ... );
}