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

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

问题描述

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

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

我怎样才能获得的关键阵列(0,1,2,3,4,5,6)

我已经尝试了很多例子,但一切都没有为我工作。

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

第四个参数 $严格,如果 TRUE ,将使用严格的类型比较。因此, 9 将无法正常工作,你就必须通过'9',因为值存储为字符串。返回比赛中第一次出现的关键, NULL 如果值没有找到,或 FALSE 上的错误。请确保使用的返回值进行严格比较的,因为 0 NULL FALSE 都是可能的返回值,如果将使用宽松的整数比较所有计算结果为 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天全站免登陆