如何在嵌套数组中查找元素并获取其子数组索引

时间:2014-03-10 07:30:57

标签: php multidimensional-array

在搜索嵌套数组中的元素时,我能否找回它的第一级嵌套索引。

<?php
static $cnt = 0;
$name = 'victor';
$coll = array(
    'dep1' => array(
        'fy' => array('john', 'johnny', 'victor'),
        'sy' => array('david', 'arthur'),
        'ty' => array('sam', 'joe', 'victor')
    ),
    'dep2' => array(
        'fy' => array('natalie', 'linda', 'molly'),
        'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
        'ty' => array('sharon', 'julia', 'maddy')
    )
);

function recursive_search(&$v, $k, $search_query){
    global $cnt;
    if($v == $search_query){
       /* i want the sub array index to be returned */
    }
}

&GT;

即,如果我正在搜索'victor',我想将'dep1'作为返回值。 谁能帮忙?

2 个答案:

答案 0 :(得分:1)

这样可行,但我不知道你是否对此感到满意......

<?php
$name = 'linda';
$col1=array ( 'dep1' => array ( 'fy' => array ( 0 => 'john', 1 => 'johnny', 2 => 'victor', ), 'sy' => array ( 0 => 'david', 1 => 'arthur', ), 'ty' => array ( 0 => 'sam', 1 => 'joe', 2 => 'victor', ), ), 'dep2' => array ( 'fy' => array ( 0 => 'natalie', 1 => 'linda', 2 => 'molly', ), 'sy' => array ( 0 => 'katie', 1 => 'helen', 2 => 'sam', 3 => 'ravi', 4 => 'vipul', ), 'ty' => array ( 0 => 'sharon', 1 => 'julia', 2 => 'maddy', ), ), );

foreach($col2 as $k=>$arr)
{
    foreach($arr as $k1=>$arr2)
    {
        if(in_array($name,$arr2))
        {
            echo $k;
            break;
        }
    }
}

<强> OUTPUT :

dept2

Demo

答案 1 :(得分:1)

尝试:

$name = 'victor';
$coll = array(
    'dep1' => array(
        'fy' => array('john', 'johnny', 'victor'),
        'sy' => array('david', 'arthur'),
        'ty' => array('sam', 'joe', 'victor')
    ),
    'dep2' => array(
        'fy' => array('natalie', 'linda', 'molly'),
        'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
        'ty' => array('sharon', 'julia', 'maddy')
    )
);

$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($coll), RecursiveIteratorIterator::SELF_FIRST);

/* These will be used to keep a record of the
   current parent element it's accessing the childs of */
$parent_index = 0;
$parent = '';
$parent_keys = array_keys($coll); //getting the first level keys like dep1,dep2
$size = sizeof($parent_keys);
$flag=0; //to check if value has been found

foreach ($iter as  $k=>$val) {
    //if dep1 matches, record it until it shifts to dep2
    if($k === $parent_keys[$parent_index]){ 
        $parent = $k;
            //making sure the counter is not incremented
            //more than the number of elements present
        ($parent_index<$size-1)?$parent_index++:'';
    }
    if ($val == $name) {
        //if the value is found, set flag and break the loop
        $flag = 1;
        break;
    }
}

($flag==0)?$parent='':''; //this means the search string could not be found
echo 'Key = '.$parent;

<强> Demo