簡體   English   中英

多維數組鍵/值

[英]Multidimensional array key/value

我在正確獲取內部數組鍵/值對時遇到問題。 我有正確的外部數組,但內部數組只是將索引號作為鍵,而不是將鍵設置為所需的鍵。 好像我錯過了內部數組的形成步驟,但我不確定它是什么...

我現在的代碼:

<?php

$path = './downloads/Current/v5.5/';
$blacklist = array('orig55205Web', 'SQL Files', '.', '..');

foreach (new DirectoryIterator($path) as $folder) {
    if($folder->isDot() || in_array($folder, $blacklist)) continue;

    if($folder->isDir()) {
        $item = $folder->getFilename();
        $versions[$item] = array();

        if ($handle = opendir($path . $item)) {
            while (false !== ($file = readdir($handle))) {
                if (!in_array($file, $blacklist)) {
                    array_push($versions[$item], $file);
                }
                asort($versions[$item]);
                $versions[$item] = array_values($versions[$item]);
            }
        }
        closedir($handle);
    }
}
ksort($versions);
print_r($versions);
?>

我的輸出當前如下所示:

Array
(
    [55106Web] => Array
        (
            [0] => 55106.txt
            [1] => ClientSetup.exe
            [2] => ClientSetup32.exe
            [3] => Setup.exe
            [4] => Setup32.exe
        )

    [55122Web] => Array
        (
            [0] => 55122.txt
            [1] => ClientSetup.exe
            [2] => ClientSetup32.exe
            [3] => Setup.exe
            [4] => Setup32.exe
        )
 )

我想輸出什么:

Array
(
    [55106Web] => Array
        (
            [Version] => 55106.txt
            [CS64] => ClientSetup.exe
            [CS32] => ClientSetup32.exe
            [S64] => Setup.exe
            [S32] => Setup32.exe
        )

    [55122Web] => Array
        (
            [Version] => 55122.txt
            [CS64] => ClientSetup.exe
            [CS32] => ClientSetup32.exe
            [S64] => Setup.exe
            [S32] => Setup32.exe
        )
 )

這里有兩個問題。 首先,您沒有做任何將基於字符串的索引分配給內部數組的操作。

其次,即使您使用了array_values ,也將刪除這些索引。從docs array_values() returns all the values from the array and indexes the array numerically.

因此,您應該分配索引(請參見下文),並刪除對array_values的調用。

這可能無法完全滿足您的需求100%,但是應該使您朝着正確的方向前進。

$indexesArray = array("Version", "CS64", "CS32", "S64", "S32");
$i = 0;
while (false !== ($file = readdir($handle))) {
    if (!in_array($file, $blacklist)) {
        $versions[$item][$indexesArray[$i]] = $file;
        $i++
    }
}
asort($versions[$item]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM