PHP~如何测试完全关联的数组

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.

To make it short, you can't because every array is implemented the same way. From the docs:

An array in PHP is actually an ordered map. A map is a type that associates values to keys.

If have no insight in the implementation, but I'm pretty sure that array(1,2,3) is just shorthand for array(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 with 0 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?

Is this what you're looking for?

<?php
function is_assoc( $array ) {
    if( !is_array( $array ) || array_keys( $array ) == range( 0, count( $array ) - 1 ) ) {
        return( false );
    }
    foreach( $array as $value ) {
        if( is_array( $value ) && !is_assoc( $value ) ) {
            return( false );
        }
    }
    return( true );
}
?>

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.