如何获得两个数组键从值在二维数组(PHP)


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

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

从这个数组中,基本上我需要创建一个带有数组值参数的函数,然后它给我数组键。

例如:

find_index('Cat');

输出:

结果是动物,1

你可以这样写

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

试试这个:

$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']));

考虑这个数组,

$arr['animal'][] = 'Dog';
$arr['animal'][] = 'Cat';
$arr['insects'][] = 'Insect1';
$arr['insects'][] = 'Insect2';

这是迭代器方法,

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