0

我有这个数组

 $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
        )

)

键的变化不会反映在最终的数组中。我该如何进行这项工作?

4

2 回答 2

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
        )

)
于 2013-09-10T08:47:16.953 回答
-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]);
}
于 2013-09-10T08:36:12.393 回答