如何在 PHP 中有效地將字串新增到數組鍵前面?

Mary-Kate Olsen
發布: 2024-10-26 20:47:02
原創
673 人瀏覽過

How to Efficiently Prepend a String to Array Keys in PHP?

數組的高效鍵前綴

要將字串加到平面數組中的所有鍵前面,請考慮以下方法:

單行解決方案:

<code class="php">$prefix = "prefix";
$array = array_combine(
    array_map(fn($k) => $prefix . $k, array_keys($array)),
    $array
);</code>
登入後複製

迭代方法:

<code class="php">$prefix = "prefix";
foreach ($array as $k => $v) {
    $array[$prefix . $k] = $v;
    unset($array[$k]);
}</code>
登入後複製

歷史方法(PHP 533 之前歷史方法(PHP 533 之前) ):

<code class="php">class KeyPrefixer {
    private $prefix;
    public function __construct($prefix) {
        $this->prefix = (string)$prefix;       
    }
    public static function prefix(array $array, $prefix) {
        $prefixer = new KeyPrefixer($prefix);
        return $prefixer->mapArray($array);
    }
    public function mapArray(array $array) {
        return array_combine(
            array_map(array($this, 'mapKey', array_keys($array)),
            $array
        );
    }
    public function mapKey($key) {
        return $this->prefix . (string)$key;
    }
}</code>
登入後複製

以上是如何在 PHP 中有效地將字串新增到數組鍵前面?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!