In PHP, the usort() function is used to sort arrays by multi-level key values. With a user-defined comparison function, it can be sorted according to key-value pairs while keeping the key names unchanged. Practical application: To sort blog comments by the number of likes, you can use usort() and the comparison function to sort in descending order by likes.
Sort arrays by multi-level key values in PHP
In PHP, sort arrays by multi-level key values Can make data processing more convenient. This tutorial shows how to sort an array by multi-level key-value pairs while keeping the key names unchanged.
Using the usort()
##usort() function sorts an array using a user-defined comparison function. We can use this function to sort the array by specified key-value pairs while maintaining the key names.
<?php function compare($a, $b) { return $a['key'] <=> $b['key']; } $data = [ 'data1' => ['key' => 10], 'data2' => ['key' => 5], 'data3' => ['key' => 15], ]; usort($data, 'compare'); print_r($data); ?>
Array ( [data2] => Array ( [key] => 5 ) [data1] => Array ( [key] => 10 ) [data3] => Array ( [key] => 15 ) )
compare(), which converts the
key of the array elements values are compared. We then use the
usort() function to sort the array by
key value.
Practical Case
Let us consider a practical case, using theusort() function to sort the comments of a blog post by the number of likes.
<?php $comments = [ 1 => ['content' => '评论 1', 'likes' => 10], 2 => ['content' => '评论 2', 'likes' => 5], 3 => ['content' => '评论 3', 'likes' => 15], ]; function compareComments($a, $b) { return $b['likes'] <=> $a['likes']; } usort($comments, 'compareComments'); foreach ($comments as $id => $comment) { echo "评论 $id: {$comment['content']}, 点赞数: {$comment['likes']}<br>"; } ?>
评论 3: 评论 3, 点赞数: 15<br> 评论 1: 评论 1, 点赞数: 10<br> 评论 2: 评论 2, 点赞数: 5<br>
compareComments() function to sort the comments array by
likes value (descending order) . We then iterate over the sorted array and display the content and number of likes for each comment.
The above is the detailed content of Sort arrays by multi-level key values in PHP, keeping key names. For more information, please follow other related articles on the PHP Chinese website!