如何对 WP Rest API 返回的 multi-dimensional 数组进行排序?
How do I sort a multi-dimensional array returned by WP Rest API?
使用 WordPress REST API,我从外部获取帖子:
https://example.com/wp-json/wp/v2/posts?orderby=date&order=desc&per_page=12
Body 结果:
[
{
"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;
}
使用 WordPress REST API,我从外部获取帖子: https://example.com/wp-json/wp/v2/posts?orderby=date&order=desc&per_page=12
Body 结果:
[
{
"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;
}