php array_merge associative arrays

后端 未结 7 1224
天命终不由人
天命终不由人 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;
    
    0 讨论(0)
  • 2020-12-09 09:02

    You could use array operator: +

    $products = array(0 => "Select a product" ) + $products;
    

    it will do a union and only works when the keys don't overlap.

    0 讨论(0)
  • 2020-12-09 09:10

    You man want to look at array_replace function.

    In this example they are function the same:

    $products1 = array (1 => 'Product 1', 42 => 'Product 42', 100 => 'Product 100');
    $products2 = array (0 => 'Select a product');
    
    $result1 = array_replace($products1, $products2);
    $result2 = $products1 + $products2;
    
    Result for both result1 and result2: Keys are preserved:
    array(4) {
      [1] => string(9) "Product 1"
      [42] => string(10) "Product 42"
      [100] => string(11) "Product 100"
      [0] => string(16) "Select a product"
    }
    

    However they differ if the same key is present in both arrays: + operator does not overwrite the value, array_replace does.

    0 讨论(0)
  • 2020-12-09 09:11

    You could try something like

    $products[0]='Select a Product'
    ksort($products);
    

    That should put the 0 at the start of the array but it will also sort the other products in numeric order which you may not want.

    0 讨论(0)
  • 2020-12-09 09:13

    From the docs:

    If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator

    The keys from the first array argument are preserved when using the + union operator, so reversing the order of your arguments and using the union operator should do what you need:

    $products = $products + array(0 => "Select a product");
    
    0 讨论(0)
  • 2020-12-09 09:19

    Just for the fun of it

    $newArray = array_combine(array_merge(array_keys($array1),
                                          array_keys($array2)
                                         ),
                              array_merge(array_values($array1),
                                          array_values($array2)
                                         )
                             );
    
    0 讨论(0)
提交回复
热议问题