使特定元素成为数组中的第一个元素

时间:2013-04-23 06:45:40

标签: php

我有一个像这样的数组

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

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

现在,我知道id的价值,如何重新安排id的特定值在顶部..(即,{{1}的值我有一个应该在数组顶部的变量,如果我得到id的值为4那么数组应该是

id

提前感谢..

4 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);

答案 2 :(得分:0)

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

usort($array, function($a,$b){ return $b['master']['id']==4; });

答案 3 :(得分:0)

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

http://codepad.org/z4oI9KHk