PHP ~ 如何测试完全关联数组
有很多方法(好的和不太好的方法)来检查关联数组,但是如何检查“完全关联”数组呢?
$john = array('name' => 'john', , 8 => 'eight', 'children' => array('fred', 'jane'));
$mary1 = array('name' => 'mary', 0 => 'zero', 'children' => array('jane'));
$mary2 = array('name' => 'mary', 'zero', 'children' => array('jane'));
这里 $john 是完全关联的,$mary1 和 $mary2 不是。
There is many - good and less good - ways to check associative arrays, but how would you check a "fully associative" array?
$john = array('name' => 'john', , 8 => 'eight', 'children' => array('fred', 'jane'));
$mary1 = array('name' => 'mary', 0 => 'zero', 'children' => array('jane'));
$mary2 = array('name' => 'mary', 'zero', 'children' => array('jane'));
Here $john is fully associative, $mary1 and $mary2 are not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简而言之,你不能,因为每个数组都是以相同的方式实现的。来自 文档:
如果对实现没有深入了解,但我很确定
array(1,2,3)
只是array(0=>1, 1=>2 的简写, 2=>3)
,即最后是一模一样的。没有什么可以区分这一点。您只能假设通过
array(value, value,...)
创建的数组具有0
索引,而其他数组则没有。但您已经看到,情况并非总是如此。每次检测“关联”数组的尝试都会在某些时候失败。
实际的问题是:为什么你需要这个?
To make it short, you can't because every array is implemented the same way. From the docs:
If have no insight in the implementation, but I'm pretty sure that
array(1,2,3)
is just shorthand forarray(0=>1, 1=>2, 2=>3)
, i.e. in the end it is exactly the same. There is nothing with which you could distinguish that.You could only assume that arrays created via
array(value, value,...)
have an index with0
and the others have not. But you have already seen that this must not always be the case.And every attempt to detect an "associative" array would fail at some point.
The actual question is: Why do you need this?
这是您要找的吗?
检测取决于您对关联的定义。此函数检查关联性,这意味着数组没有连续的数字键。有些人可能会说关联是指隐式设置键而不是由 php 计算的任何键。其他人甚至可能将所有 PHP 数组定义为关联数组(在这种情况下,
is_array()
就足够了)。同样,这一切都取决于,但这是我在项目中使用的函数。希望它对您来说足够好。Is this what you're looking for?
The detection depends on your definition of associative. This function checks for the associative that means arrays that don't have sequential numeric keys. Some may say that associative is anything where the key was implicitly set instead of calculated by php. Others may even define all PHP arrays as associative (in which case
is_array()
would have sufficed). Again, it all depends, but this is the function I use in my projects. Hopefully, it's good enough for you.