我有一个foreach循环,可以找到评论回复并将其存储在$child_comments
之后
<?php echo '<pre>';
print_r($child_comments);
echo '</pre>'; ?>
我为每个父评论获得了一个单独的数组:
Array
(
[0] => stdClass Object
(
[comment_ID] => 603
[comment_parent] => 600
[user_id] => 2
)
[1] => stdClass Object
(
[comment_ID] => 601
[comment_parent] => 600
[user_id] => 2
)
)
Array
(
[0] => stdClass Object
(
[comment_ID] => 584
[comment_parent] => 580
[user_id] => 1
)
)
Array
(
[0] => stdClass Object
(
[comment_ID] => 608
[comment_parent] => 520
[user_id] => 2
)
[1] => stdClass Object
(
[comment_ID] => 598
[comment_parent] => 520
[user_id] => 2
)
[2] => stdClass Object
(
[comment_ID] => 521
[comment_parent] => 520
[user_id] => 2
)
)
但我需要按照评论ID排序并输出评论,从最高ID到最低ID。
我可以通过
获得我喜欢的评论foreach ($child_comments as $objects) {
echo $objects->comment_ID;
}
但他们仍将根据其父评论进行排序。有任何想法吗?理想的结构是这样的:
Array
(
[0] => stdClass Object
(
[comment_ID] => 608
[comment_parent] => 520
[user_id] => 2
)
[1] => stdClass Object
(
[comment_ID] => 603
[comment_parent] => 600
[user_id] => 2
)
[2] => stdClass Object
(
[comment_ID] => 601
[comment_parent] => 600
[user_id] => 2
)
[3] => stdClass Object
(
[comment_ID] => 598
[comment_parent] => 520
[user_id] => 2
)
[4] => stdClass Object
(
[comment_ID] => 584
[comment_parent] => 580
[user_id] => 1
)
[5] => stdClass Object
(
[comment_ID] => 521
[comment_parent] => 520
[user_id] => 2
)
)
答案 0 :(得分:2)
如果您获得不同comments
中的每个arrays
,那么首先您可以使用array_merge()创建单个数组,然后使用usort()来sort
您的最终版本数组,
<?php
$comments=array_merge($child_comments);
function cmp($a, $b) {
return $b['comment_ID'] - $a['comment_ID'];//use $b->comment_ID if Object
}
usort($comments, "cmp");
print_r($comments);
?>
答案 1 :(得分:0)
如果您有复杂的排序标准,最好的方法是使用usort进行回调。
例如:
usort($arrayOfObjects, function($a, $b){
if($a->comment_parent > $b->comment_parent) return 1;
elseif($a->comment_parent < $b->comment_parent) return -1;
else{
// Do child compare here...
}
});