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

后端 未结 6 1972
萌比男神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

    You could do it by splitting your array using array_keys and array_values, then splice them both, then combine them again.

    $insertKey = 'k1';
    
    $keys = array_keys($arr);
    $vals = array_values($arr);
    
    $insertAfter = array_search($insertKey, $keys) + 1;
    
    $keys2 = array_splice($keys, $insertAfter);
    $vals2 = array_splice($vals, $insertAfter);
    
    $keys[] = "myNewKey";
    $vals[] = "myNewValue";
    
    $newArray = array_merge(array_combine($keys, $vals), array_combine($keys2, $vals2));
    

提交回复
热议问题