add value to array to particular key position and shift rest of array to right
本问题已经有最佳答案,请猛点这里访问。
我有一个数组
1 | Array ( [0] => xyz [1] => 93049 [2] => London [3] => Telephone: 45687654 [4] => Telefax: 54478453248 [5] => [6] => ) |
现在,我想在键位置[1]添加一个空白值,并将数组的其余部分移到右侧,如
1 | Array ( [0] => xyz [1] => [2] => 93049 [3] => London [4] => Telephone: 45687654 [5] => Telefax: 54478453248 [6] => [7] => ) |
号
我怎样才能用PHP做到这一点。请建议。
array_splice()函数将解决您的问题。
试试这个:
1 2 3 4 5 |
号
原始数组:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | Array ( [0] => xyz [1] => 93049 [2] => London [3] => Telephone: 45687654 [4] => Telefax: 54478453248 [5] => [6] => ) $pos = 1; // Position where you want to insert $string = ''; // The string you want to insert array_splice($original, $pos, 0, ''); print_r($original); |
最终输出:
1 2 3 4 5 6 7 8 9 10 11 | Array ( [0] => xyz [1] => [2] => 93049 [3] => London [4] => Telephone: 45687654 [5] => Telefax: 54478453248 [6] => [7] => ) |
。
1 2 3 | $original = array( '0', '2', '3', '4', '5' ); $inserted = array( '1' ); array_splice( $original, 1, 0, $inserted ); |
1 2 3 4 5 6 | <?php $arr = Array("xyz","93049","London","Telephone: 45687654","Telefax: 54478453248","","" ); $new = Array("" ); array_splice( $arr,1,0,$new ); // INSERT THE $NEW ARRAY IN POSITION 1. var_dump( $arr ); ?> |
结果如下:
1 2 3 4 5 6 7 8 9 | array (size=8) 0 => string 'xyz' (length=3) 1 => string '' (length=0) 2 => string '93049' (length=5) 3 => string 'London' (length=6) 4 => string 'Telephone: 45687654' (length=19) 5 => string 'Telefax: 54478453248' (length=20) 6 => string '' (length=0) 7 => string '' (length=0) |
。
或:
1 | Array ( [0] => xyz [1] => [2] => 93049 [3] => London [4] => Telephone: 45687654 [5] => Telefax: 54478453248 [6] => [7] => ) |
。
你可以任意地把一个你认为是黑空间的值…
例如,我武断地认为,当单词"blank"出现时,这是一个空白…所以:
阵列([0]=>XYZ[1]=>空白[2]=>93049[3]=>伦敦[4]=>电话:45687654[5]=>传真:54478453248[6]=>[7]=>……
这不是一个明确的解决方法,但是如果你不寻找最干净的方法,它就会解决。