为什么可以';t I array_将具有键的数组与对象数组组合


Why can't I array_combine an array with keys with an array of objects?

我正在尝试使用array_combine()一个数组作为键($filenames),两个数组作为组合数组对象($tags and $cfContents):

$filenames = array();
$tags = array();
$cfContents = array();
// For loop creates three arrays based on each of the set objects
foreach( new DirectoryIterator('./cf_templates/') as $cfFile )
{
    if ( $cfFile->isDot() || !$cfFile->isFile() ) continue;
        $filenames[] = $cfFile->getBasename( '.txt' );
        $tags[] = array( "<!-- " . $cfFile->getBasename( '.txt') . " CF BEGIN -->",
                     "<!-- " . $cfFile->getBasename( '.txt') . " CF END -->" );
        $cfContents[] = file_get_contents( './cf_templates/' . $cfFile. '.txt' );
}
    // $sets = array_combine( $filenames, $tags )           // This works.
    $setContent = array_merge( $tags, $cfContents );
    $sets = array_combine( $filenames, $setContent );       // Errors on "Both parameters should have an equal number of elements"

    print_r( $sets );

然而,当我运行这个程序时,数组$sets上不断出现警告(请参阅注释)。我可以想象,$setContent合并这两个数组很好,但问题是$sets??(请参见http://php.net/manual/en/function.array-combine.php)

帮助-为什么我在array_combine()上的$set不起作用?

此行:

$setContent = array_merge( $tags, $cfContents );

创建一个数组($setContent),其大小是$tags、$cfContents或$filename的两倍。因此,当您调用array_component时,$filename中没有足够的值作为结果数组的键。

我认为你误解了array_merge的行为。它创建一个平面数组,其中包含params中给定的两个数组的值。也许我可以建议这样做:

$setContent = array($tags, $cfContents);
$sets = array_combine( $filenames, $setContent );
print_r( $sets );