我想替换一些键,我的数组是:
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值!”
无论如何,谢谢。此致
答案 0 :(得分: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);
答案 1 :(得分: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"
}
}
答案 2 :(得分: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设置为您想要的任意数量的数组。