-1

我有一个按值排序的数组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
                }

          }

我想采用具有priority=的元素o并在最后追加而不用活动元素更改排序。输出应该是这样的:

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
                }

          }

键的顺序无关紧要。

4

2 回答 2

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);
于 2013-05-29T18:04:21.477 回答
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(); 
}
于 2013-05-29T18:18:16.547 回答