niz*_*zle 14 php arrays associative
我的阵列:
$data = array('two' => 2, 'one' => 1, 'three' => 3);
Run Code Online (Sandbox Code Playgroud)
现在,当我迭代数组时,将出现的第一个值可能是
$data['two'] // = 2 @ index[0]
Run Code Online (Sandbox Code Playgroud)
对?
如果我想将$ data [1]移动到$ data [0]的位置怎么办?
改写:
如何使数组看起来像这样(以便'$'出现在$ data [0])
$data = array('one' => 1, 'two' => 2, 'three' => 3
Run Code Online (Sandbox Code Playgroud)
我为什么需要这个?
我使用代码点火器,table-> generate内置函数接受一个assoc数组并创建一个表,但不提供排列列的方法.这就是我想移动源数组中的列的原因.
Die*_*ino 14
两种可能的解决方案(不使用array_splice):
1)使用新的键顺序创建一个新数组.
$new_keys = array('one', 'two', 'three');
$new_data = array();
foreach ($new_keys as $key) {
$new_data[$key] = $data[$key];
}
$data = $new_data;
Run Code Online (Sandbox Code Playgroud)
2)one预先移动元素,将其从中移除$data并复制数组的其余部分.
function rearrangeData($data) {
$result['one'] = $data['one'];
unset($data['one']);
return array_merge($result, $data);
}
$data = rearrangeData($data);
Run Code Online (Sandbox Code Playgroud)
看一下daniele centamore对PHP的array_splice()函数的评论,他在其中提供了几个函数来移动非关联数组中的元素。
<?php
// $input (Array) - the array containing the element
// $index (int) - the index of the element you need to move
function moveUp($input,$index) {
$new_array = $input;
if((count($new_array)>$index) && ($index>0)){
array_splice($new_array, $index-1, 0, $input[$index]);
array_splice($new_array, $index+1, 1);
}
return $new_array;
}
function moveDown($input,$index) {
$new_array = $input;
if(count($new_array)>$index) {
array_splice($new_array, $index+2, 0, $input[$index]);
array_splice($new_array, $index, 1);
}
return $new_array;
}
$input = array("red", "green", "blue", "yellow");
$newinput = moveUp($input, 2);
// $newinput is array("red", "blue", "green", "yellow")
$input = moveDown($newinput, 1);
// $input is array("red", "green", "blue", "yellow")
?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23823 次 |
| 最近记录: |