php array_merge associative arrays

后端 未结 7 1267
天命终不由人
天命终不由人 2020-12-09 08:41

I\'m trying to prepend an item to the beginning of an associative array. I figured the best way to do this is to use array_merge, but I\'m having some odd consequences. I

7条回答
  •  盖世英雄少女心
    2020-12-09 09:00

    array_merge will recalculate numeric indexes. Because your associative array iuses numeric indexes they will get renumbered. You either insert a non-numeric charadter in front of the indices like:

    $products = array ('_1' => 'Product 1', '_42' => 'Product 42', '_100' => 'Product 100');
    

    Or you can create the resulting array manually:

    $newproducts = array (0 => "Select a product");
    foreach ($products as $key => $value)
        $newproducts[$key] = $value;
    

提交回复
热议问题