Foreach循环+关联数组

时间:2011-12-06 03:07:24

标签: php

如果我有以下代码:

$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";

foreach( $employeeAges as $name => $age){
    echo "Name: $name, Age: $age <br />";
}

如何输出特定信息?下面是一个错误的例子:

foreach( $employeeAges as $name => $age ) {
     $selective = $name["Lisa"]->$age;
     $secondary = $name["Grace"]->$age;
     echo "The person you're looking for is $selective years old. And the other one is $secondary years old.";
}

如您所见,我只想获取特定$ key的$ value。上面的代码输出以下错误:

Trying to get property of non-object 

有人可以帮忙解决这段代码吗?非常感谢。

3 个答案:

答案 0 :(得分:4)

如果我理解你是对的,而你只是想要了解某个人的年龄,那就这样做:

$selective = $employeeAges["Lisa"];
$secondary = $employeeAges["Grace"];
echo "The person you're looking for is $selective years old. And the other one is $secondary years old.";

->运算符用于访问对象的命名成员。请参阅:http://www.php.net/manual/en/language.oop5.basic.php

如评论中所述,要迭代数组以查找特定键,请执行:

foreach ($employeeAges as $name => $age) {
    if ($name == "Grace") {
        echo $name . " is " . $age . " years old";
        break;
    }
}

答案 1 :(得分:2)

我用不同的方式解释了这个问题

<?php
//Assuming this is your array

$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";

echo $employeeAges["Lisa"]; //Will output 28
echo $employeeAges["Jack"]; //Will output 16
echo $employeeAges["Grace"]; //Will output 34

您只需指定所需的密钥,它就会输出值。

答案 2 :(得分:1)

所以你想打印出这个年龄?

$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";

$ employeeAges [“Grace”] =“34”;

foreach($employeeAges as $name=>$age) {
  echo $age;
}

使用foreach循环,只需将密钥强制转换为$name,将值强制转换为$age,而不必调用对象,从而导致错误。

我认为@jli有一个更适合你问题的答案。