简体   繁体   English

如何从二维数组(PHP)中的值获取两个数组键

[英]How to get both array key from value in 2 dimensional array (PHP)

$arr['animal'][0] = 'Dog';
$arr['animal'][1] = 'Cat';

From that array basically I need to create a function with the array value parameter and then it gives me the array keys. 基本上,我需要从该数组创建一个带有数组value参数的函数,然后为我提供数组键。

For example: 例如:

find_index('Cat');

Output : 输出:

The result is animal, 1 结果是动物,1

You could probably do something like 您可能会做类似的事情

function find_index($value) {
  foreach ($arr as $index => $index2) {
    $exists = array_search($value, $index2);
    if ($exists !== false) {
      echo "The result is {$index}, {$exists}";
      return true;
    }
  }
  return false;
}

Try this: 尝试这个:

$arr['animal'][0] = 'Dog';
$arr['animal'][1] = 'Cat';

function find_index($searchVal, $arr){
    return array_search($searchVal, $arr);
}

print_r(find_index('Cat', $arr['animal']));

Consider this Array, 考虑这个数组,

$arr['animal'][] = 'Dog';
$arr['animal'][] = 'Cat';

$arr['insects'][] = 'Insect1';
$arr['insects'][] = 'Insect2';

Here is Iterator Method, 这是迭代器方法,

$search = 'InsectSub1';
$matches = [];

$arr_array = new RecursiveArrayIterator($arr);
$arr_array_iterator = new RecursiveIteratorIterator($arr_array);

foreach($arr_array_iterator as $key => $value)
{
    if($value === $search)
    {
        $fill = [];
        $fill['category'] = $arr_array->key();
        $fill['key'] = $arr_array_iterator->key();
        $fill['value'] = $value;
        $matches[] = $fill;
    }
}

if($matches)
{
    // One or more Match(es) Found
}
else
{
    // Not Found
}
$arr['animal'][] = 'Dog';
$arr['animal'][] = 'Cat';
$arr['insects'][] = 'Insect1';
$arr['insects'][] = 'Insect2';

$search_for = 'Cat';
$search_result = [];

while ($part = each($arr)) {
    $found = array_search($search_for, $part['value']);
    if(is_int($found)) {
        $fill = [ 'key1' => $part['key'], 'key2' => $found ];
        $search_result[] = $fill;
    }
}

echo 'Found '.count($search_result).' result(s)';
print_r($search_result);

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

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