1

我有这个(我只显示三个记录,还有很多很多)

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)

4

5 回答 5

2

你可以使用foreach

foreach($phoneList as $item)
{
  if($item['department'] == 'Falmouth')
  {
    echo $phoneList['name'] . '<br>';
    echo $phoneList['telephonenumber'] . '<br>';
    echo $phoneList['department'] . '<br><br>';
  }
}
于 2012-06-13T14:34:55.753 回答
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>';
    }
}
于 2012-06-13T14:35:04.520 回答
1
try
foreach($phoneList as $key => $data)
{

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

}
于 2012-06-13T14:34:56.407 回答
1
$testNeedle = 'DepartmentS';
foreach( array_filter( $phonelist,
                       function($arrayEntry) use ($testNeedle) {
                           return $arrayEntry['department'] === $testNeedle;
                       }
         ) as $phoneEntry) {
    var_dump($phoneEntry);
}
于 2012-06-13T14:43:35.800 回答
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>';
    }
}
于 2012-06-13T14:52:01.703 回答