>  기사  >  php教程  >  Sort Objects by Property with?PHP

Sort Objects by Property with?PHP

WBOY
WBOY원래의
2016-06-06 20:08:512060검색

I recently needed to display a list of authors within a WordPress blog. ?The goal was to sort the author list by number of posts before outputting the list. ?The method for calculating number of posts isnt a sortable key within WordPress g

I recently needed to display a list of authors within a WordPress blog. ?The goal was to sort the author list by number of posts before outputting the list. ?The method for calculating number of posts isn’t a sortable key within WordPress’ get_posts, so I had to sort the result list myself. ?PHP’s usort method, along with a custom function, allows you to accomplish the feat of sorting a collection of objects by key.

The PHP

The first step is creating the function that does the sorting — this is that function:

function sort_objects_by_total($a, $b) {
	if($a->total_posts == $b->total_posts){ return 0 ; }
	return ($a->total_posts total_posts) ? -1 : 1;
}

The function returns -1 (smaller than), 0 (equal to), or 1 (larger than) when doing the sort comparisons. ?The last is applying the sortation function to the array, which is done by usort:

usort($users, 'sort_objects_by_total');

The code above now ensures that my authors array is sorted by total_posts. ?Keep this snippet in your PHP toolbox for the future — I’m certain you’ll need it at one time or another.

Read the full article at: Sort Objects by Property with PHP

Treehouse

Sencha Conference

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.