我有以下代码可以很好地为我提供ID为10的客户名称:
foreach($customer_list as $row) {
if ($row->CUSTOMER_ID == 10)
echo $row->NAME;
}
有没有一种方法可以更直接地做到这一点,没有foreach循环和if语句?我想做类似的事情:
echo $customer_list[CUSTOMER_ID][10]->NAME;
但我不知道语法或者它是否可能。
答案 0 :(得分:2)
您可以使用array_filter
它将返回ID为10的客户数组。然后我们选择第一个匹配项(可能是唯一的匹配项)并访问NAME
属性。
$name = reset( array_filter(
$customer_list,function($c){return $c->CUSTOMER_ID === 10;}
))->NAME;
更清洁的方法是将其分解为一个单独的函数:
$getCustName = function($list,$id){
return reset( array_filter(
$list,
function($c) use ($id) {return $c->CUSTOMER_ID === $id;}
))->NAME;
};
然后你只需一行即可轻松获得名称:
$name = $getCustName($customer_list,10);
答案 1 :(得分:0)
您可以使用php array_filter方法。 基本上你需要传递一个函数来检查customer_Id的值并返回数组的元素。
答案 2 :(得分:0)
您可以在函数中添加代码,然后在需要名称时调用该函数。我假设您有唯一的客户ID。
function getCustName($customers,$id){
if(count($customers)>0){
foreach($customers as $row) {
if ($row->CUSTOMER_ID == $id)
return $row->NAME;
}
} else{
return false;
}
}
现在,如果您需要获取客户名称,只需调用函数
即可echo getCustName($customer_list,10);