2013-03-01 62 views
4

對於前有此數組:關聯數組 - 改變位置

[food] => Array (
    [fruits] => apple 
    [vegetables] => garlic 
    [nuts] => cashew 
    [meat] => beaf 
) 

我需要改變一個特定的鍵值組合的位置。

比方說,我需要[水果] =>蘋果移動到第三的位置

[food] => Array (
    [vegetables] => garlic 
    [nuts] => cashew 
    [fruits] => apple 
    [meat] => beaf 
) 

我不是在談論的鍵或值排序。 我需要將鍵值的位置更改爲非常嚴格的新位置。

喜歡的東西:

change_pos($my_arr, $key_to_move, $new_index); 

=>

change_pos($my_arr, "fruits", 3); 

這可能嗎?

回答

6

這是很難的,但最後:

<?php 
function array_splice_assoc(&$input, $offset, $length, $replacement) { 
     $replacement = (array) $replacement; 
     $key_indices = array_flip(array_keys($input)); 
     if (isset($input[$offset]) && is_string($offset)) { 
       $offset = $key_indices[$offset]; 
     } 
     if (isset($input[$length]) && is_string($length)) { 
       $length = $key_indices[$length] - $offset; 
     } 

     $input = array_slice($input, 0, $offset, TRUE) 
       + $replacement 
       + array_slice($input, $offset + $length, NULL, TRUE); 
} 
function array_move($which, $where, $array) 
{ 
    $tmpWhich = $which; 
    $j=0; 
    $keys = array_keys($array); 

    for($i=0;$i<count($array);$i++) 
    { 
     if($keys[$i]==$tmpWhich) 
      $tmpWhich = $j; 
     else 
      $j++; 
    } 
    $tmp = array_splice($array, $tmpWhich, 1); 
    array_splice_assoc($array, $where, 0, $tmp); 
    return $array; 
} 
$array = array('fruits' => 'apple','vegetables' => 'garlic','nuts' => 'cashew','meat' => 'beaf'); 
$res = array_move('vegetables',2,$array); 
var_dump($res); 
?> 
+0

是否適用於無數字索引?你可以使用http://phpfiddle.org – 2013-03-01 22:05:08

+0

提供演示示例這不能正常工作,不要移動其他元素的索引 – Sam 2013-03-01 22:07:39

+0

編輯,努力工作,但完成。 – MIIB 2013-03-01 22:34:51

2

我要感謝MIIB爲他的辛勤工作!我會接受他的辛勤工作的答案。

但我想出了一個更適合我的解決方案,我會使用它。

function ksort_arr (&$arr, $index_arr) { 
    $arr_t=array(); 
    foreach($index_arr as $i=>$v) { 
     foreach($arr as $k=>$b) { 
      if ($k==$v) $arr_t[$k]=$b; 
     } 
    } 
    $arr=$arr_t; 
} 

$arr=array("fruits"=>"apple","vegetables"=>"garlic","nuts"=>"cashew","meat"=>"beaf"); 
$index_arr=array("vegetables","meat","fruits","nuts"); 
ksort_arr($arr,$index_arr); 
print_r($arr); 

結果

Array 
(
    [vegetables] => garlic 
    [meat] => beaf 
    [fruits] => apple 
    [nuts] => cashew 
) 
0

下面是使用的第二陣列一個更簡單的解決方案。它還爲新的索引參數提供了一些基本驗證。僅用於關聯數組。與數字數組一起使用是沒有意義的。

function array_move($key, $new_index, $array) 
{ 
    if($new_index < 0) return; 
    if($new_index >= count($array)) return; 
    if(!array_key_exists($key, $array)) return; 

    $ret = array(); 
    $ind = 0; 
    foreach($array as $k => $v) 
    { 
     if($new_index == $ind) 
     { 
     $ret[$key] = $array[$key]; 
     $ind++; 
     } 
     if($k != $key) 
     { 
     $ret[$k] = $v; 
     $ind++; 
     } 
    } 
    // one last check for end indexes 
    if($new_index == $ind) 
     $ret[$key] = $array[$key]; 


    return $ret; 
}