php array re populate keys

后端 未结 3 1590
野趣味
野趣味 2020-12-22 05:09

Hi I have an array, I need to change the keys, in an orderly manner but don\'t change the order the values are. e.g.

$a = array (
 0=>\'h\',
 1=>\'blab         


        
相关标签:
3条回答
  • 2020-12-22 05:22

    You need to apply array_values on your array to re-index.

    $a = array_values($a);
    

    Bonus: If you also need to order your values you can use sort and it too will re-index your array.

    Note: By using any of array_values or sort you will loose any string keys you may have.

    0 讨论(0)
  • 2020-12-22 05:24

    Call array_values on it:

    $a = array (
     0=>'h',
     1=>'blabla',
     2=>'yes'
    );
    
    unset($a[1]);
    
    $a = array_values($a);
    
    var_dump($a); 
    /*
    array(2) {
      [0]=>
      string(1) "h"
      [1]=>
      string(3) "yes"
    }
    */
    
    0 讨论(0)
  • 2020-12-22 05:25

    You can also use array_splice() instead of unset(), which will automatically reindex the array elements:

    $a = array (
     0=>'h',
     1=>'blabla',
     2=>'yes'
    );
    
    array_splice($a,1,1);
    
    var_dump($a);
    
    0 讨论(0)
提交回复
热议问题