我有这个数组
$the_posted = Array
(
0 => Array
(
0 => 1,
1 => 2,
2 => 3,
3 => 4,
),
1 => Array
(
0 => 5,
1 => 6,
2 => 7,
3 => 8,
)
);
我需要修改其中的键。我试图修改数组键,如
$all_array_keys = array_keys($the_posted);
foreach ( array_keys($the_posted) as $k=>$v )
{
$all_array_keys[$k]= rand();
}
echo '<pre>';
print_r($all_array_keys);
echo "<hr/>";
print_r($the_posted);
echo '<pre>';
我得到了这个结果
Array
(
[0] => 25642
[1] => 8731
)
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
[1] => Array
(
[0] => 5
[1] => 6
[2] => 7
[3] => 8
)
)
键中的更改不会反映在最终数组中。我如何使其工作?。
答案 0 :(得分:1)
您可以使用以下代码:
foreach ( array_keys($the_posted) as $k=>$v )
{
$new_key = rand();
$new_posted[$new_key] = $the_posted[$v];
unset($the_posted[$v])
}
在这里,我们创建了一个新的数组$new_posted
,它将包含带有这样的新键的数据:
Array
(
[28228] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
[23341] => Array
(
[0] => 5
[1] => 6
[2] => 7
[3] => 8
)
)
答案 1 :(得分:-1)
要更改项目的键,请执行以下操作:
$the_posted[$newkey] = $the_posted[$oldkey];
unset($the_posted[$oldkey]);
所以在你的情况下:
foreach ( $the_posted as $k=>$v )
{
$newkey = rand();
while(isset($the_posted[$newkey]))
$newkey = rand();
$the_posted[$newkey] = $the_posted[$k];
unset($the_posted[$k]);
}