如何排序由WP Rest API返回的多维数组?



使用WordPress REST API,我在外部获得帖子:https://example.com/wp-json/wp/v2/posts?orderby=date&订单= desc& per_page = 12

身体结果:

[
{
"date": "2022-05-05T12:12:12",
"link": "https://example.com/blog/132/",
"title": {
"rendered": "F: Title"
}
},
{
"date": "2022-04-04T12:12:12",
"link": "https://example.com/blog/434/",
"title": {
"rendered": "E: Title"
}
},
{
"date": "2022-03-03T12:12:12",
"link": "https://example.com/blog/324/",
"title": {
"rendered": "A: Title"
}
},
etc...
]

我想把标题按字母顺序排序。

最好的解决方案是什么?

我无法使用WP_Query,因为帖子是从外部WP API源中提取的。

可能是这样的:

<?php
function cmp($a, $b)
{
if ($a['title']['rendered'] == $b['title']['rendered']) {
return 0;
}
return ($a['title']['rendered'] < $b['title']['rendered']) ? -1 : 1;
}
$ar = json_decode($yourJson, TRUE);
usort($ar, "cmp");
...
?>

使用此函数对任意数组进行排序

function array_sort($array, $on, $order = SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}

foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}

相关内容

  • 没有找到相关文章

最新更新