How to efficiently insert elements after another known (by key or pointer) element in a PHP array?

后端 未结 6 1951
萌比男神i
萌比男神i 2021-02-07 11:01

Given an array:

$a = array(
    \'abc\',
    123,
    \'k1\'=>\'v1\',
    \'k2\'=>\'v2\',
    78,
    \'tt\',
    \'k3\'=>\'v3\'
);

Wi

6条回答
  •  时光说笑
    2021-02-07 11:58

    This way is fine for new values without keys. You can not insert value with a key, and numeric indexes will be 'reset' as 0 to N-1.

    $keys = array_keys($a);
    $index = array_flip($keys);
    
    $key = key($a); //current element
    //or 
    $key = 'k1';
    
    array_splice($a, $index[$key] + 1, 0, array('value'));
    

提交回复
热议问题