2012-06-13 88 views
0

我有這個(我只顯示三條記錄,還有很多很多)騎自行車通過關聯數組的數組

Array 
(
[0] => Array 
    (
     [name] => Johnson, John 
     [telephonenumber] => 555.555.555 
     [department] => Department A 
    ) 

[1] => Array 
    (
     [name] => Johnson, Bill 
     [telephonenumber] => 555.555.4444 
     [department] => Department B 
    ) 

[2] => Array 
    (
     [name] => Johnson, Carry 
     [telephonenumber] => 555.555.3333 
     [department] => Department C 
    ) 
) 

會有廳A,B,等我的多個成員需要遍歷這些數據,並吐出僅系A的成員我曾嘗試:

if ($phoneList['department'] == 'Falmouth') { 
    echo $phoneList['name'] . '<br>'; 
    echo $phoneList['telephonenumber'] . '<br>'; 
    echo $phoneList['department'] . '<br><br>'; 
} 

但我得到的錯誤,因爲我覺得$phoneList['department']不存在(不應該$phoneList[0]['department'])?

無論哪種方式,這將無濟於事......我如何搜索所有90個這樣的數組,並只打印出具有Department A狀態的數組?

$ PHONELIST被傳遞給我的看法變量(使用笨,LDAP和PHP)

+3

迭代和檢查'department',還是我在這裏可以俯瞰什麼? – Josh

+0

是的,那就是我正在做的......但是我正在使用=而不是==,並且它把所有東西都扔掉了!有時候我只需要寫點東西來解決它......感謝評論! – ClaytonDaniels

回答

2

你可以使用foreach

foreach($phoneList as $item) 
{ 
    if($item['department'] == 'Falmouth') 
    { 
    echo $phoneList['name'] . '<br>'; 
    echo $phoneList['telephonenumber'] . '<br>'; 
    echo $phoneList['department'] . '<br><br>'; 
    } 
} 
+0

這就是我所擁有的,除了我=而不是==!感謝您的迴應! – ClaytonDaniels

1
try 
foreach($phoneList as $key => $data) 
{ 

    if($data['department'] == 'DepartmentA') 
    { 
     ... 
    } 

} 
2

我敢肯定喬希具有它是正確的,你應該使用類似的東西:

foreach($phoneList as $item) { 
    if($item['department'] == 'Falmouth') { 
     echo $item['name'] . '<br>'; 
     echo $item['telephonenumber'] . '<br>'; 
     echo $item['department'] . '<br><br>'; 
    } 
} 

你甚至可以更換呼叫foreach循環的內部部分implode()

foreach($phoneList as $item) { 
    if($item['department'] == 'Falmouth') { 
     echo implode('<br>', $item) . '<br><br>'; 
    } 
} 
1
$testNeedle = 'DepartmentS'; 
foreach(array_filter($phonelist, 
         function($arrayEntry) use ($testNeedle) { 
          return $arrayEntry['department'] === $testNeedle; 
         } 
     ) as $phoneEntry) { 
    var_dump($phoneEntry); 
} 
0

對於這些類型的問題,「array_walk」可以被使用。你應該調用下面寫的功能 -

array_walk($phoneList, 'print_department'); 

功能是:使用`foreach`

function print_department($phonelist){ 

    // Printing the items 
    if($phonelist['department'] == 'Falmouth'){ 
     echo $phonelist['name']. '<br>'; 
     echo $phonelist['telephonenumber']. '<br>'; 
     echo $phonelist['department']. '<br>'; 
    } 
}