簡體   English   中英

如何更改數組鍵的一部分?

[英]How to change the part of array key?

我正在跟蹤名為$_FILES數組:

Array
(
    [document_file_name_2] => Array
        (
            [name] => FAQ.doc
            [type] => application/msword
            [tmp_name] => /tmp/phpDnXqMX
            [error] => 0
            [size] => 35840
        )

    [document_file_name_5] => Array
        (
            [name] => Pay Slip-Sushil Kadam-June 2013.pdf
            [type] => application/pdf
            [tmp_name] => /tmp/php97sAKI
            [error] => 0
            [size] => 39648
        )

)

由於此數組是動態生成的,因此其長度可能會有所不同。 現在,我要實現的是更改現有陣列鍵的某些部分。 我想使陣列鍵從鍵[document_file_name_0] ,依此類推。 以下數組應在進行操作后出現。 誰能幫我實現這個目標? 以下是所需的$_FILES數組:

Array
    (
        [document_file_name_0] => Array
            (
                [name] => FAQ.doc
                [type] => application/msword
                [tmp_name] => /tmp/phpDnXqMX
                [error] => 0
                [size] => 35840
            )

        [document_file_name_1] => Array
            (
                [name] => Pay Slip-Sushil Kadam-June 2013.pdf
                [type] => application/pdf
                [tmp_name] => /tmp/php97sAKI
                [error] => 0
                [size] => 39648
            )

    )

提前致謝。

$newArray=array();
$fileNum=0;
foreach ($originalArray as $file) {
    $newArray["document_file_name".$fileNum++]=$file;
}

$ newArray的內容應該是您想要的

使用array_values獲取數組中的值

創建一個新數組並遍歷array_values並在新數組中設置custom_key => value對

$counter = 0;
foreach ($array as $key => $values) {
  if ($key != 'document_file_name_' . $counter) { // If by coincidence this one is correct already, no need to rename/delete the original
    $array['document_file_name_' . $counter] = $array[$key];
    unset($array[$key]);
  }
  $counter++;
}

我知道選擇了最好的(根據OP)問題,但是我仍然很想說,您可以為此使用幾乎所有的php循環:

由@RubenSerrate編寫的foreach()

$newArray=array();
$fileNum=0;
foreach ($originalArray as $file) {
    $newArray["document_file_name".$fileNum++]=$file;
}

for()phpfiddle

$newArr = array();
$length = count($_FILES);
for ($i=0; $i<$length; $i++) {
    $newArr["document_file_name_".$i] = array_shift($_FILES);
}

而()

$newArr = array();
$i=0;
while ($_FILES) {
    $newArr["document_file_name_".$i] = array_shift($_FILES);
    $i++;
}

+所有其他示例+所有其他尚未提及的方法。

只要學習PHP並祝您好運!

暫無
暫無

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

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