我的代码:
$customers='[
{
"id": 1,
"name": "sara",
"phone": 1100,
"mobile": 1111
},
{
"id": 2,
"name": "ben",
"phone": 2200,
"mobile": 2222
}
]';
$data = json_decode($customers, true);
foreach($data as $a){
if($a['name'] == 'sara'){
$phone = $a['phone'];
$mobile = $a['mobile'];
echo "sara's phone is $phone";
echo "sara's mobile is $mobile";
}
else{
echo "No customer found with this name";
}
}
我的问题是:只有其他部分在工作,如果条件不工作但当我移除其他部分,如果部分工作良好。你能帮我吗?用false
创建布尔变量
遍历数组并使此变量为true
,以防用户找到。
在最后检查变量的最终值,如果它是false
,则显示消息No customer found.
这是一个动态函数方法:
$data = json_decode($customers, true);
function findCustomerInArr($array,$customerName){
$customerFound = false;
foreach($array as $a){
if(strtolower($a['name']) == strtolower($customerName)){
$customerFound = true;
echo $customerName."'s phone is ".$a['phone'].PHP_EOL;
echo $customerName."'s mobile is ".$a['mobile'].PHP_EOL;
break;
}
}
if(false == $customerFound){
echo "No customer found with this name".PHP_EOL;
}
}
findCustomerInArr($data,'sara');
findCustomerInArr($data,'aliveToDie');
输出:https://3v4l.org/fIJXu
注意:如果需要区分大小写的匹配,可以删除strtolower()
。
您可以这样编写循环和条件,它可能会解决问题。
$customers = '[
{
"id": 1,
"name": "sara",
"phone": 1100,
"mobile": 1111
},
{
"id": 2,
"name": "ben",
"phone": 2200,
"mobile": 2222
}
]';
$data = json_decode($customers, true);
$phone = Null;
$mobile = Null;
$name="sara";
foreach ($data as $a) {
if ($a['name'] == $name) {
$phone = $a['phone'];
$mobile = $a['mobile'];
break;
}
}
if ($phone != Null && $mobile != Null) {
echo "$name's phone is $phone n";
echo "$name's mobile is $mobile";
}else{
echo "No customer found with this name";
}