2011-12-06 204 views
1

如果我有以下代碼:Foreach循環+關聯數組

$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的$值。上面的代碼輸出以下錯誤:

Trying to get property of non-object 

有人可以幫助這段代碼?不勝感激。

回答

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; 
    } 
} 
+0

+1爲鏈接上' - >' – Jon

+0

尷尬,謝謝!我只是現在試圖用for循環而不是每個for循環。當它達到格雷斯並輸出她的年齡時,是否有可能做到並斷裂? – Sara

+0

當然,但它擊敗了關聯數組的目的。我會通過如何更新我的答案。 – jli

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有一個更好的答案適合您的問題,但。

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 

你只需要指定你想要的關鍵問題,它將輸出值。