确定数组是否为关联(散)或不 [英] Determine whether an array is associative (hash) or not

查看:80
本文介绍了确定数组是否为关联(散)或不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能到一个数组传递给一个函数,并有功能不同的表现取决于它是否是一个清单的风格数组或一个哈希的风格数组。例如:

I'd like to be able to pass an array to a function and have the function behave differently depending on whether it's a "list" style array or a "hash" style array. E.g.:

myfunc(array("One", "Two", "Three")); // works
myfunc(array(1=>"One", 2=>"Two", 3=>"Three")); also works, but understands it's a hash

魔法门输出是这样的:

Might output something like:

One, Two, Three
1=One, 2=Two, 3=Three

即:函数做一些不同的东西,当检测到它正在通过哈希,而不是一个数组。你能告诉我是从一个Perl的背景,其中%哈希从@arrays不同的引用来了?

ie: the function does something differently when it "detects" it's being passed a hash rather than an array. Can you tell I'm coming from a Perl background where %hashes are different references from @arrays?

我相信我的例子是显著,因为我们不能仅仅测试看关键是数字的,因为你很可能在你的哈希使用数字键。

I believe my example is significant because we can't just test to see whether the key is numeric, because you could very well be using numeric keys in your hash.

我专门找避免使用 MYFUNC(数组的混乱结构(阵列(1 =>中一),阵列(2 =>中二),数组(3 =>中三)))

推荐答案

拉右出Kohana的框架。

Pulled right out of the kohana framework.

public static function is_assoc(array $array)
{
    // Keys of the array
    $keys = array_keys($array);

    // If the array keys of the keys match the keys, then the array must
    // not be associative (e.g. the keys array looked like {0:0, 1:1...}).
    return array_keys($keys) !== $keys;
}

这篇关于确定数组是否为关联(散)或不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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