gpt4 book ai didi

php - Foreach循环+关联数组

转载 作者:行者123 更新时间:2023-12-04 13:46:27 24 4
gpt4 key购买 nike

如果我有以下代码:

$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 


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

最佳答案

如果我理解的正确,并且您只想确定某个人的年龄,请执行以下操作:

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

关于php - Foreach循环+关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8394876/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com