如何在foreach循环中选择“子数组”

ale*_*non 3 php arrays foreach

我有一个数组数组

$person = array(2) {
      [billy]=>
        array(3) {
          ["height"]=>
          string(60) "tall"
          ["build"]=>
          string(7) "slim"
         ["attractiveness"]=>
         string(7) "extremely"
      }
    [carl]=>
      array(3) {
        ["height"]=>
        string(60) "short"
        ["build"]=>
        string(7) "chubby"
        ["attractiveness"]=>
        string(7) "neglegible"
   }
Run Code Online (Sandbox Code Playgroud)

不幸的是,卡尔对他没有任何兴趣。相反,比利非常受欢迎,人们希望看到比利的详细信息。

所以我想遍历数组并只返回比利的信息。

function findHotty($billy){
   foreach ( $person as $meat)
   {
      // wizardry 
      return onlyBilly
   }
}
Run Code Online (Sandbox Code Playgroud)

我希望在函数中传递子数组的名称,所以如果明天 Carl 风靡一时——他有某种不可否认的魅力——当我调用该方法时,我可以将它传递给 Carl,它会寻找他的子数组。我希望这很清楚!

sha*_*hat 5

不需要任何循环,尽管您应该实现某种错误检查以确保该名称存在于 people 数组中。

function findHotty($name) {
    if (!isset($person[$name])) {
        // do something when the name doesn't exist
    }
    return $person[$name];
}
Run Code Online (Sandbox Code Playgroud)