【问题标题】:How to get both array key from value in 2 dimensional array (PHP)如何从二维数组(PHP)中的值中获取数组键
【发布时间】:2015-07-07 03:50:52
【问题描述】:
$arr['animal'][0] = 'Dog';
$arr['animal'][1] = 'Cat';

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

例如:

find_index('Cat');

输出:

结果是动物,1

【问题讨论】:

  • 如果这是您的代码的主要目的,您的数据结构很可能是错误的……您能解释一下为什么需要这样做吗?

标签: php html arrays multidimensional-array


【解决方案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;
}

【讨论】:

  • 那么与 OP Question 有什么联系??
  • Mindastic:为什么要中断而不是返回?阿卜杜拉:嗯,这正是 OP 要求的……
  • 哈哈!我不知道,我刚开始编写函数并没有考虑返回选项,但同意,返回会更好。立即更改。
  • (1) 这目前存在变量范围问题,除非数组$arr 被添加到函数内部或作为函数参数。 (2)$index2是一个数组,所以echo "The result is {$index}, {$index2}";会返回一个Array to string conversion的通知,以及一个The result is animal, Array的响应。通过将foreach ($index2 as $val) 更改为foreach ($index2 as $key => $val)echo "The result is {$index}, {$index2}"; 更改为echo "The result is {$index}, {$key}"; 轻松解决
  • 我改变了我的答案,但我所做的与@Sean 提出的解决方案明显不同(不过这很好)。检查是否有效。
【解决方案2】:

试试这个:

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

【讨论】:

    【解决方案3】:

    考虑这个数组,

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

    【讨论】:

      【解决方案4】:
      $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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多