欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

php array_unshift key and value 添加键值对 设置键 有大用


PHP: array_unshift With Key | array unshift Associative Array

Useful code allowing you to prepend a key/value pair to an array (without the keys being reindexed) :

<?php 
    $myArray = array($key => $value) + $myArray;
?>

array_unshift with key
array_unshift associative array
array unshift assoc

up vote98down votefavorite                    
14                    

Is it possible to prepend an associative array with literal key=>value pairs? I know that array_unshift() works with numerical keys, but I'm hoping for something that will work with literal keys.

As an example I'd like to do the following:

$array1 = array('fruit3'=>'apple', 'fruit4'=>'orange');
$array2 = array('fruit1'=>'cherry', 'fruit2'=>'blueberry');

// prepend magic

$resulting_array = ('fruit1'=>'cherry', 
                    'fruit2'=>'blueberry', 
                    'fruit3'=>'apple', 
                    'fruit4'=>'orange');
               
shareimprove this question                            
       

4 Answers 正确答案                

activeoldestvotes                    
       
up vote187down voteaccepted                    

Can't you just do:

$resulting_array = $array2 + $array1;
                       

?

shareimprove this answer                            
  • 13                                    
    See also array_merge() and its difference from using the + operator: br.php.net/manual/en/function.array-merge.php#92602 – Havenard Sep 3 '09 at 1:33                                    
  • 2                                    
    @cletus: Sheesh. Yeah, I can. Not sure what made me think I couldn't or what wasn't working before. Thanks for the response. – Colin Brock Sep 3 '09 at 1:36                                    
  • 1                                    
    @Havenard: Thanks for the additional info. – Colin Brock Sep 3 '09 at 1:36                                    
  • It is worth noting the difference but that difference is relevant for preserving numeric keys and this array is a "pure" associative array with string keys. – cletus Sep 3 '09 at 1:37                                    
       
up vote20down vote                    

The answer is no. You cannot prepend an associative array with a key-value pair.

However you can create a new array that contains the new key-value pair at the beginning of the array with the union operator +. The outcome is an entirely new array though and creating the new array has O(n) complexity.

The syntax is below.

$new_array = array('new_key' => 'value') + $original_array;
                       

Note: Do not use array_merge(). array_merge() overwrites keys and does not preserve numeric keys.

shareimprove this answer                            
       
up vote16down vote                    

In your situation, you want to use array_merge():

array_merge(array('fruit1'=>'cherry', 'fruit2'=>'blueberry'), array('fruit3'=>'apple', 'fruit4'=>'orange'));
                       

To prepend a single value, for an associative array, instead of array_unshift(), again use array_merge():

array_merge(array($key => $value), $myarray);
                   
shareimprove this answer                            
       
up vote5down vote                    

@Cletus is spot on. Just to add, if the ordering of the elements in the input arrays are ambiguous, and you need the final array to be sorted, you might want to ksort:

$resulting_array = $array1 + $array2;
ksort($resulting_array);
                   
shareimprove this answer                            
  • @karim: That's helpful - thanks. – Colin Brock Sep 3 '09 at 1:38                                    
  • 4                                    
    As a late note, ksort returns boolean, so the above needs to be done as two statements not one, e.g. $a = $array1 + $array2; ksort($a);, otherwise $resulting_array will be a boolean value not the array you were expecting. – El Yobo Oct 17 '11 at 22:39                                    
       

来自  https://stackoverflow.com/questions/1371016/php-prepend-associative-array-with-literal-keys            


           

Prepend key value to array - PHP                

up vote1down votefavorite                            

I have the below code in a for..loop is there a way I can add values to the beginning of the array?

    $data = array();

    $initial = strtotime('11:00:00');
    for (; $initial < strtotime("23:00:59");  $initial = strtotime("+15 minutes", $initial)) {
        if ($initial > strtotime("+45 minutes", time())) {
            $row['value'] = date('Hi', $initial);
            $row['label'] = date('H:i', $initial);
            $data['data'][] = $row;
        }
    }
                               

I want to add the below values to the top of the array. I have tried using array_unshift but I don't think it supports key-value pairs.

    if(!isBetween('22:00', '09:59', date('H:i'))) {
        $row['value'] = "asap";
        $row['label'] = "ASAP";
    }
                               

My array output

{
  "data": [
    {
      "value": "1145",
      "label": "11:45"
    }
  ]
}
                               

I want to get this

{
  "data": [
    {
      "value": "asap",
      "label": "ASAP"
    },{
      "value": "1145",
      "label": "11:45"
    },
  ]
}
                           
shareimprove this question                                        
                   

2 Answers 

正确答案

                           

activeoldestvotes                                
                   
up vote2down voteaccepted                                

Un-shift should work if you pass the arguments correctly:

array_unshift($data["data"], $prepend);
                                   

Alternatively, you could use array_merge, like this:

$data["data"] = array_merge(array($prepend), $data["data"]);
                                   

With the following example data:

$data = [
    "data" => [
        [
            "value" => "1145",
            "label" => "11:45"
        ]
    ]
];

$prepend = [
    "value" => "asap",
    "label" => "ASAP"
];

$data["data"] = array_merge(array($prepend), $data["data"]);
print_r($data);
                                   

You would get this output (with both solutions):

Array (
    [data] => Array (
            [0] => Array (
                    [value] => asap
                    [label] => ASAP
                )
            [1] => Array (
                    [value] => 1145
                    [label] => 11:45
                )
        )
)
                               
shareimprove this answer                                        
  • Thanks! Works correctly – moh_abk Dec 22 '15 at 11:13                                                
  • 1                                                
    NB: But you could also use unshift still. For me this works: array_unshift($data["data"], $prepend);– trincot Dec 22 '15 at 11:14                                                
                   
up vote0down vote                                

If you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:

function array_unshift_assoc(&$arr, $key, $val) { 
    $arr = array_reverse($arr, true); 
    $arr[$key] = $val; 
    return = array_reverse($arr, true); 
} 
                                   

Source: http://php.net/manual/en/function.array-unshift.php                                    

shareimprove this answer                                        
                   

来自  https://stackoverflow.com/questions/34413984/prepend-key-value-to-array-php


       


普通分类: