如何从数组中删除一个元素并使用php追加到最后

时间:2013-05-29 17:42:52

标签: php arrays sorting

我有一个按active值排序的数组,如下所示:

patient = Array {

    [0] = Array {
           active = Y
           priority = o
                },

    [1] = Array {
           active = Y
           priority = P
                },

    [2] = Array {
           active = Y
           priority = S
                },

    [3] = Array {
           active = Y
           priority = T
                },

    [4] = Array {
           active = N
           priority = S
                }

          }

我想获取优先级为o的元素,并在最后添加,而不用使用active元素进行排序更改。输出应该是这样的:

patient = Array {

    [1] = Array {
           active = Y
           priority = P
                },

    [2] = Array {
           active = Y
           priority = S
                },

    [3] = Array {
           active = Y
           priority = T
                },

    [0] = Array {
           active = Y
           priority = o
                },

    [4] = Array {
           active = N
           priority = S
                }

          }

密钥的顺序无关紧要。

2 个答案:

答案 0 :(得分:1)

您需要的是:http://www.php.net/manual/en/function.uasort.php

// Comparison function
function cmp_priority($a, $b) {
    if ($a['priority'] == $b['priority']) {
        return 0;
    }
    return $a['priority'] == 'o' ? -1 : 1;
}

// Sort and print the resulting array using the comparison function
uasort($patient, 'cmp_priority');
print_r($patient);

答案 1 :(得分:0)

您可能希望从阵列到优先级队列,因为它针对该任务进行了优化。 但请记住,PQ在所有安装中都不可用。 http://php.net/manual/en/class.splpriorityqueue.php

$objPQ = new SplPriorityQueue();
$objPQ->insert('A',3); 
$objPQ->insert('B',6); 
$objPQ->insert('C',1); 
$objPQ->insert('D',2); 

//mode of extraction 
$objPQ->setExtractFlags(PQtest::EXTR_BOTH); 

//Go to TOP 
$objPQ->top(); 

while($objPQ->valid()){ 
    print_r($objPQ->current()); 
    echo "<BR>"; 
    $objPQ->next(); 
}