PHP将所有数组都视为关联数组,因此没有任何内置函数。谁能推荐一种相当有效的方法来检查数组是否“是一个列表”(只包含从0开始的数字键)?
基本上,我希望能够区分这些:
$sequentialArray = [
'apple', 'orange', 'tomato', 'carrot'
];
这:
$assocArray = [
'fruit1' => 'apple',
'fruit2' => 'orange',
'veg1' => 'tomato',
'veg2' => 'carrot'
];
这个问题实际上在php数组中是没有用的,因为php的本质是数组不应该是完全关联的或索引的,它可以是两者的组合,用户定义和赋值数组的方式可以是两者的组合。参见下面的示例
$y= array(5);
$y["0x"]="n";
$y["vbg"]="12132";
$y[1] = "k";
var_dump($y); //this will output 4 element array
echo "</br>" .$y["0x"]."</br>".$y[0];
for($x=0;$x<sizeof($y);$x++){ // this will output all index elements & gives error after that
echo "</br> index elements ".$y[$x];
}
正确的问题是,数组中的所有元素都是关联的还是下标的。如果你真的知道它只能是关联数组或索引数组而不是两者的组合,你可以简单地使用这个方法来确定它是索引数组还是关联数组。
function AssocTest(&$arr){
if(is_array($arr)){
reset($arr); // reset pointer to first element of array
if(gettype(key($arr)) == "string"){ //get the type(nature) of first element key
return true;
}else{
return false;
}
}else{
return false;
}
}
你可以正常使用它
echo(AssocTest($y)? "Associative array": "Not an Associative array/ Not an array at all");
重要的是,evan,你已经初始化了一个关联数组但是你给关联数组的名字只是数字当它被PHP读取时它会被当作一个索引数组如果你没有显式地给字符串名字。看看下面的例子。
$y["0"]="n";
$y["1"]="12132";
$y["22"] = "k";
//both will get the same output
echo "<br/> s0 ".$y["22"];
echo "<br/> s0 ".$y[22];
for($x=0;$x<count($y);$x++){
echo "<br/> arr ".$y[$x]; // this will output up to 2nd element and give an error after
}
如果你需要确保数组中的所有元素都被精确索引,或者是关联的,没有其他方法,只能对所有元素赋真,并检查每个元素键通过生成索引数组,就像这里很多人发布的那样。
function fullAssocTest(&$arr)
{
if(is_array($arr)){
return (array_keys($arr) !== range(0, count($arr) - 1));
}
}
它的代码更少,但这个东西真的是过程密集和真正不必要的工作。
Mark Amery的改进
function isAssoc($arr)
{
// Is it set, is an array, not empty and keys are not sequentialy numeric from 0
return isset($arr) && is_array($arr) && count($arr)!=0 && array_keys($arr) !== range(0, count($arr) - 1);
}
这个测试变量是否存在,是否为数组,是否为空数组,以及键是否从0开始连续。
来查看数组是否是关联的
if (isAssoc($array)) ...
看看它是不是数值
if (!isAssoc($array)) ...
我认为标量数组的定义因应用程序而异。也就是说,一些应用程序将需要更严格的定义标量数组,而一些应用程序将需要更宽松的定义。
下面我将介绍3种不同严格程度的方法。
<?php
/**
* Since PHP stores all arrays as associative internally, there is no proper
* definition of a scalar array.
*
* As such, developers are likely to have varying definitions of scalar array,
* based on their application needs.
*
* In this file, I present 3 increasingly strict methods of determining if an
* array is scalar.
*
* @author David Farrell <DavidPFarrell@gmail.com>
*/
/**
* isArrayWithOnlyIntKeys defines a scalar array as containing
* only integer keys.
*
* If you are explicitly setting integer keys on an array, you
* may need this function to determine scalar-ness.
*
* @param array $a
* @return boolean
*/
function isArrayWithOnlyIntKeys(array $a)
{
if (!is_array($a))
return false;
foreach ($a as $k => $v)
if (!is_int($k))
return false;
return true;
}
/**
* isArrayWithOnlyAscendingIntKeys defines a scalar array as
* containing only integer keys in ascending (but not necessarily
* sequential) order.
*
* If you are performing pushes, pops, and unsets on your array,
* you may need this function to determine scalar-ness.
*
* @param array $a
* @return boolean
*/
function isArrayWithOnlyAscendingIntKeys(array $a)
{
if (!is_array($a))
return false;
$prev = null;
foreach ($a as $k => $v)
{
if (!is_int($k) || (null !== $prev && $k <= $prev))
return false;
$prev = $k;
}
return true;
}
/**
* isArrayWithOnlyZeroBasedSequentialIntKeys defines a scalar array
* as containing only integer keys in sequential, ascending order,
* starting from 0.
*
* If you are only performing operations on your array that are
* guaranteed to either maintain consistent key values, or that
* re-base the keys for consistency, then you can use this function.
*
* @param array $a
* @return boolean
*/
function isArrayWithOnlyZeroBasedSequentialIntKeys(array $a)
{
if (!is_array($a))
return false;
$i = 0;
foreach ($a as $k => $v)
if ($i++ !== $k)
return false;
return true;
}
A lot of the solutions here are elegant and pretty, but don't scale well, and are memory intensive or CPU intensive. Most are creating 2 new data points in memory with this solution from both sides of the comparison. The larger the array the harder and longer the process and memory used, and you lose the benefit of short circuit evaluation. I Did some testing with a few different ideas. Trying to avoid array_key_exists as it is costly, and also avoiding creating new large datasets to compare. I feel this is a simple way to tell if an array is sequential.
public function is_sequential( $arr = [] ){
if( !is_array( $arr ) || empty( $arr ) ) return false;
$i = 0;
$total = count( $arr );
foreach( $arr as $key => $value ) if( $key !== $i++ ) return false;
return true;
}
在主数组上运行一个计数并存储一个整数。然后循环遍历数组并在迭代计数器时检查精确匹配。你应该从1开始计数。如果它失败了,它会短路,当它为假时,它会给你性能的提升。
最初,我这样做了一个for循环和检查isset($arr[$ I]),但这将不检测null键,这需要array_key_exists,我们知道,这是最糟糕的函数使用速度。
通过foreach不断更新变量,并检查迭代器,永远不会超过它的整数大小,让PHP使用它内置的内存优化,缓存和垃圾收集,以保持非常低的资源使用。
此外,我认为在foreach中使用array_keys是愚蠢的,因为您可以简单地运行$key => $value并检查键。为什么要创建新的数据点?一旦抽象出数组键,就会立即消耗更多内存。
这是函数-
public function is_assoc_array($array){
if(is_array($array) !== true){
return false;
}else{
$check = json_decode(json_encode($array));
if(is_object($check) === true){
return true;
}else{
return false;
}
}
}
一些例子
print_r((is_assoc_array(['one','two','three']))===true?'Yes':'No'); \\No
print_r(is_assoc_array(['one'=>'one','two'=>'two','three'=>'three'])?'Yes':'No'); \\Yes
print_r(is_assoc_array(['1'=>'one','2'=>'two','3'=>'three'])?'Yes':'No'); \\Yes
print_r(is_assoc_array(['0'=>'one','1'=>'two','2'=>'three'])?'Yes':'No'); \\No
在其中一个答案中@devios1有一个类似的解决方案,但这只是使用PHP的内置json相关函数的另一种方式。我还没有检查这个解决方案在性能方面如何与其他已经在这里发布的解决方案相比。但它确实帮助我解决了这个问题。希望这能有所帮助。