0

我想替换一些键,我的数组是:

Array
(
    [0] => Array
        (
            [0] => test1
            [1] => test2
            [2] => test3
            [3] => test4
            [4] => test5
            [5] => test6
        )

    [1] => Array
        (
            [0] => test7
            [1] => test8
            [2] => test9
            [3] => test10
            [4] => test11
            [5] => test12
        )

)

我的希望:

Array
(
    [45] => Array
        (
            [0] => test1
            [1] => test2
            [2] => test3
            [3] => test4
            [4] => test5
            [5] => test6
        )

    [51] => Array
        (
            [0] => test7
            [1] => test8
            [2] => test9
            [3] => test10
            [4] => test11
            [5] => test12
        )

)

图 45 和 51 是示例。

我怎样才能做到这一点?我尝试了 array_flip() 然后 array_search() 但 PHP 说:“只能翻转 STRING 和 INTEGER 值!”

不管怎么说,还是要谢谢你。问候

4

3 回答 3

1
$old_array = array(
    0 => array(0=>'test1',1=>'test2',2=>'test3',3=>'test4',4=>'test5',5=>'test6'),
    1 => array(0=>'test1',1=>'test2',2=>'test3',3=>'test4',4=>'test5',5=>'test6')
);
$new_array = array(
    45=>$old_array[0],
    51=>$old_array[1]
);
var_dump($new_array);
于 2012-11-25T22:27:11.670 回答
1

可以通过将新键设置为旧键的值然后取消设置旧键来修改数组中的键。

$myArray = array(
    "0" => array("0" => "test1", "1" => "test2"),
    "1" => array("0" => "test3", "1" => "test4"));

echo "original array:\n";
var_dump($myArray);

// modify keys
$myArray["45"] = $myArray["0"];
unset($myArray["0"]);
$myArray["51"] = $myArray["1"];
unset($myArray["1"]);

echo "modified array:\n";
var_dump($myArray);

生成:

original array:
array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "test1"
    [1]=>
    string(5) "test2"
  }
  [1]=>
  array(2) {
    [0]=>
    string(5) "test3"
    [1]=>
    string(5) "test4"
  }
}

modified array:
array(2) {
  [45]=>
  array(2) {
    [0]=>
    string(5) "test1"
    [1]=>
    string(5) "test2"
  }
  [51]=>
  array(2) {
    [0]=>
    string(5) "test3"
    [1]=>
    string(5) "test4"
  }
}
于 2012-11-25T22:28:11.650 回答
0
$keys = array('45','51');
$count = 6 ;
$i = 0;
foreach($keys as $key){
   for($l = 0;$l<$count;$l++){
      $last[$key][$l] = 'test'.$l+$i+1 ;
   }
  $i += $count;
}
print_r($last);

将 $count 设置为您想要的任意数量的数组。

于 2012-11-25T22:39:56.893 回答