我有一个带有n个元素的索引数组:
Array(
'key1' => 'value1',
'key2' => 'value1',
'key3' => 'value1',
...
'key<i-1>' => 'value<i-1>',
'key<i>' => 'value<i>',
'key<i+1>' => 'value<i+1>',
...
'key<n>' => 'value<n>'
)
如何“剪切”(即:复制+删除)i_th元素,使结果数组为:
Array(
'key1' => 'value1',
'key2' => 'value1',
'key3' => 'value1',
...
'key<i-1>' => 'value<i-1>',
'key<i+1>' => 'value<i+1>',
...
'key<n>' => 'value<n>'
)
我知道array_pop()和array_shift()PHP函数,但有一个通用的按键“剪切”元素吗?
谢谢。
答案 0 :(得分:3)
您可以使用以下代码检索然后删除其索引处的元素:
function array_cut(&$array, $key) {
if(!isset($array[$key])) return null;
$keyOffset = array_search($key, array_keys($array));
$result = array_values(array_splice($array, $keyOffset, 1));
return $result[0];
}
然后您可以这样使用它:
echo "Numerically Index Test:\n";
$a = array(0,1,2,3,4,5,6);
echo array_cut($a, 2) . "\n";
var_dump($a);
echo "------------------------------\n";
echo "Assosiative Index Test:\n";
$b = array('hello' => 'world', 'how' => 'like that', 'where' => 'Stack Overflow');
echo array_cut($b, 'how') . "\n";
var_dump($b);
输出:
Numerically Index Test:
2
array(6) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
[5]=>
int(6)
}
------------------------------
Assosiative Index Test:
like that
array(2) {
["hello"]=>
string(5) "world"
["where"]=>
string(14) "Stack Overflow"
}
答案 1 :(得分:2)
unset($myarray['mykey']);
答案 2 :(得分:1)
array_splice()可能有空替换?