获取多维数组的键? [英] Get key of multidimensional array?

查看:30
本文介绍了获取多维数组的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有如下多维数组:

For example, I have multidimensional array as below:

$array = array (
  0 => 
    array (
      'id' => '9',
      'gallery_id' => '2',
      'picture' => '56475832.jpg'
    ),
  1 => 
    array (
      'id' => '8',
      'gallery_id' => '2',
      'picture' => '20083622.jpg'
    ),
  2 => 
    array (
      'id' => '7',
      'gallery_id' => '2',
      'picture' => '89001465.jpg'
    ),
  3 => 
    array (
      'id' => '6',
      'gallery_id' => '2',
      'picture' => '47360232.jpg'
    ),
  4 => 
    array (
      'id' => '5',
      'gallery_id' => '2',
      'picture' => '4876713.jpg'
    ),
  5 => 
    array (
      'id' => '4',
      'gallery_id' => '2',
      'picture' => '5447392.jpg'
    ),
  6 => 
    array (
      'id' => '3',
      'gallery_id' => '2',
      'picture' => '95117187.jpg'
    )
);

如何获取array(0,1,2,3,4,5,6)的key?

我尝试了很多例子,但没有一个对我有用.

I have tried a lot of examples, but nothing has worked for me.

推荐答案

这个很简单,你只需要使用array_keys():

This is quite simple, you just need to use array_keys():

$keys = array_keys($array);

看到它工作

编辑对于您的搜索任务,此功能应该可以完成工作:

EDIT For your search task, this function should do the job:

function array_search_inner ($array, $attr, $val, $strict = FALSE) {
  // Error is input array is not an array
  if (!is_array($array)) return FALSE;
  // Loop the array
  foreach ($array as $key => $inner) {
    // Error if inner item is not an array (you may want to remove this line)
    if (!is_array($inner)) return FALSE;
    // Skip entries where search key is not present
    if (!isset($inner[$attr])) continue;
    if ($strict) {
      // Strict typing
      if ($inner[$attr] === $val) return $key;
    } else {
      // Loose typing
      if ($inner[$attr] == $val) return $key;
    }
  }
  // We didn't find it
  return NULL;
}

// Example usage
$key = array_search_inner($array, 'id', 9);

第四个参数$strict,如果TRUE,将使用严格的类型比较.所以 9 将不起作用,您必须传递 '9',因为这些值存储为字符串.返回匹配项第一次出现的键,NULL 如果没有找到该值,或者 FALSE 出现错误.确保对返回值使用严格的比较,因为 0NULLFALSE 都是可能的返回值,它们都会评估为0 如果使用松散整数比较.

The fourth parameter $strict, if TRUE, will use strict type comparisons. So 9 will not work, you would have to pass '9', since the values are stored as strings. Returns the key of the first occurence of a match, NULL if the value is not found, or FALSE on error. make sure to use a strict comparison on the return value, since 0, NULL and FALSE are all possible return values and they will all evaluate to 0 if using loose integer comparisons.

这篇关于获取多维数组的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆