php 在foreach循环中无法工作

mctunoxg  于 2023-04-04  发布在  PHP
关注(0)|答案(2)|浏览(167)

我的代码:

$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";
    }
}

我的问题是:只是其他部分是工作,如果条件不工作,但当我删除其他部分,如果部分工作良好。你能帮助我吗??

9q78igpj

9q78igpj1#

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()

xwbd5t1u

xwbd5t1u2#

你可以像这样编写循环和条件,它可以解决这个问题。

$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";
}

相关问题