首頁 >後端開發 >php教程 >取消設定元素後如何重新排序數組鍵?

取消設定元素後如何重新排序數組鍵?

Susan Sarandon
Susan Sarandon原創
2024-10-29 09:16:30935瀏覽

How to Reorder Array Keys After Unsetting Elements?

取消設定元素後重新排序數組鍵

取消數組中的元素時,數組鍵可能會變得脫節,從而影響索引順序。要解決此問題,您可以使用 array_values() 方法。

請考慮以下程式碼:

<code class="php">$array = array(1, 2, 3, 4, 5);

foreach ($array as $i => $info) {
    if ($info == 1 || $info == 2) {
        unset($array[$i]);
    }
}

print_r($array); // Outputs: [3, 4, 5] (disjointed keys)</code>

要重新指派鍵,請使用array_values():

<code class="php">$array = array_values($array);

print_r($array); // Outputs: [0 => 3, 1 => 4, 2 => 5] (reordered keys)</code>

array_values() 建立一個新數組,其中保留值且鍵從零索引開始,有效地重新排序數組鍵。

以上是取消設定元素後如何重新排序數組鍵?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn