繁体   English   中英

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

[英]how to find a element in a nested array and get its sub array index

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

<?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 */
    }
}

?>

也就是说,如果我正在搜索“胜利者”,我想将“ dep1”作为返回值。 谁能帮忙??

这可行,但是我不知道你是否同意...

<?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

演示

尝试:

$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;

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM