我有这个(我只显示三个记录,还有很多,更多)
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个这些阵列,只打印出那些有A部门状态的阵列?
$ phoneList是传递给我视图的变量(使用codeigniter,ldap和php)
答案 0 :(得分:2)
您可以使用foreach
:
foreach($phoneList as $item)
{
if($item['department'] == 'Falmouth')
{
echo $phoneList['name'] . '<br>';
echo $phoneList['telephonenumber'] . '<br>';
echo $phoneList['department'] . '<br><br>';
}
}
答案 1 :(得分:2)
我很确定Josh说得对,你应该使用类似的东西:
foreach( $phoneList as $item) {
if( $item['department'] == 'Falmouth') {
echo $item['name'] . '<br>';
echo $item['telephonenumber'] . '<br>';
echo $item['department'] . '<br><br>';
}
}
您甚至可以通过调用implode()
来替换foreach循环的内部部分:
foreach( $phoneList as $item) {
if( $item['department'] == 'Falmouth') {
echo implode( '<br>', $item) . '<br><br>';
}
}
答案 2 :(得分:1)
try
foreach($phoneList as $key => $data)
{
if($data['department'] == 'DepartmentA')
{
...
}
}
答案 3 :(得分:1)
$testNeedle = 'DepartmentS';
foreach( array_filter( $phonelist,
function($arrayEntry) use ($testNeedle) {
return $arrayEntry['department'] === $testNeedle;
}
) as $phoneEntry) {
var_dump($phoneEntry);
}
答案 4 :(得分:0)
对于这些类型的问题,也可以使用'array_walk'。您应该将以下书面函数调用为 -
array_walk($phoneList, 'print_department');
功能是:
function print_department($phonelist){
// Printing the items
if($phonelist['department'] == 'Falmouth'){
echo $phonelist['name']. '<br>';
echo $phonelist['telephonenumber']. '<br>';
echo $phonelist['department']. '<br>';
}
}