搜索多维数组

时间:2013-09-09 08:57:55

标签: php arrays multidimensional-array

我有这样的数组

$lists=
Array ( 
[0] => Array ( [item] => Global ISDN Switchtype = primary-net5 ) 
[1] => Array ( [item] => ISDN Serial0/0/0:15 interface ) 
[2] => Array ( [item] => dsl 0, interface ISDN Switchtype = primary-net5 ) 
[3] => Array ( [item] => Layer 1 Status: ) 
[4] => Array ( [item] => ACTIVE ) 
[5] => Array ( [item] => Layer 2 Status: ) 
[6] => Array ( [item] => TEI = 0, Ces = 1, SAPI = 0, State = MULTIPLE_FRAME_ESTABLISHED ) 
[7] => Array ( [item] => Layer 3 Status: ) 
[8] => Array ( [item] => 13 Active Layer 3 Call(s) ) 
[9] => Array ( [item] => CCB:callid=122A, sapi=0, ces=0, B-chan=22, calltype=VOICE ) 
[10] => Array ( [item] => CCB:callid=126D, sapi=0, ces=0, B-chan=17, calltype=VOICE ) 
[11] => Array ( [item] => CCB:callid=1279, sapi=0, ces=0, B-chan=24, calltype=VOICE ) 
[12] => Array ( [item] => CCB:callid=12C5, sapi=0, ces=0, B-chan=1, calltype=VOICE ) 
[13] => Array ( [item] => CCB:callid=12D5, sapi=0, ces=0, B-chan=5, calltype=VOICE ) 
[14] => Array ( [item] => ACTIVE ) 
) 

我如何获得ACTIVE的返回值索引?

搜索数组($ lists,'ACTIVE');结果是4,14

非常感谢!

3 个答案:

答案 0 :(得分:1)

试试这个:

$result=array();
$count=count($lists);
for($i=0;$i<$count;$i++) {
  if($lists[$i]['item']=='ACTIVE') {
    $result[]=$i;
  }
}
$result=implode(",",$result);

答案 1 :(得分:1)

在PHP 5.5上,只要您使用连续的整数键索引数组,就可以使用方便的

$indexes = array_keys(array_column($lists, 'item'), 'ACTIVE');

或者,您可以使用array_walk。解决方案有点冗长,但它有许多优点:

  • 适用于PHP&gt; = 5.3
  • 无论$lists中的键是什么
  • ,都可以使用
  • 使用更少的内存(只有在阵列非常大时才真正重要)

代码:

$indexes = array();
array_walk($lists, function($i, $key) use (&$indexes) {
               if ($i['item'] == 'ACTIVE') $indexes[] = $key;
           });

<强> See it in action

答案 2 :(得分:0)

<?
// $lists is your array

function q($item, $key) {
  if ($item == 'ACTIVE')
    echo $key.", ";
}

array_walk_recursive($lists, 'q');
?>