1

我有一个这样的数组

$arrList = Array ( 
     [0] => Array
        (
          [master] => Array
                (
                  [id] => 3
                  [name] => Test
                )
        )

     [1] => Array
        (
          [master] => Array
                (
                  [id] => 4
                  [name] => Sample
                )
        )
  )

现在,我知道 的值,我id怎样才能重新排列特定的值,id使其位于顶部..(即,无论id我在应该位于数组顶部的变量中的值是什么,如果我得到的值为id4 那么数组应该是

$arrList = Array ( 
         [0] => Array
            (
              [master] => Array
                    (
                      [id] => 4
                      [name] => Sample
                    )
            )

         [1] => Array
            (
              [master] => Array
                    (
                      [id] => 3
                      [name] => Test
                    )
            )
      )

提前致谢..

4

4 回答 4

1
function cmp($a, $b)
{
    if ($a['master']['id'] == $b['master']['id']) {
        return 0;
    }

    return ($a['master']['id'] > $b['master']['id']) ? -1 : 1;
}


$a = Array ( 
        0 => Array   (
          'master' => Array
                (
                  'id' => 3,
                  'name' => 'Test',
                )
        ),

     '1' => Array
        (
          'master' => Array
                (
                  'id' => 4,
                  'name' => 'Sample',
                )
        )
  );

usort($a, "cmp");


print_r($a);
于 2013-04-23T07:32:33.977 回答
1

试试这段代码

foreach($arrList as $Key => $array) {
    if($id == $array['master']['id']){ //check the value with all [master][id]
         $arr[] = $array; // setting up the respective array to another array
         $iKey = $Key; // getting the key value of that particular array
    }
}
if(isset($iKey) && $iKey != NULL){
    unset($arrList[$iKey]); // removing the key value from the main array
    array_splice($arrList, 0, 0, $arr);
    //using this function setting up again the array to the 0th index,
}

对于任何其他索引值,在上述函数中作为第二个参数提及,假设如果您需要作为第三个索引,那么它应该是..

array_splice($arrList, 3, 0, $arr);
于 2013-04-23T10:42:30.663 回答
0

您可以使用特殊的排序功能对数组进行排序。代码是:

usort($array, function($a,$b){ return $b['master']['id']==4; });
于 2013-04-23T06:54:53.453 回答
0

试试这个,我在这里创建了示例

http://codepad.org/z4oI9KHk

于 2013-04-23T07:22:30.443 回答