将维基百科API搜索结果排序为数组


Sorting Wikipedia API search results into an array

以以下代码为例:

$wikisearch = "http://en.wikipedia.org/w/api.php?action=opensearch&search=inception";
$wikisearchlist = file_get_contents($wikisearch);
echo $wikisearchlist;

我得到这个:

[
    "inception",
    [
        "Inception",
        "Inception Motorsports",
        "Inception of Darwin's theory",
        "Inception (soundtrack)",
        "Inception (McCoy Tyner album)",
        "Inception (Download album)",
        "Inception/Nostalgia",
        "Inception date",
        "Inception (disambiguation)"
    ]
]

我想首先删除开头的查询("inception"),然后解码JSON以创建一个包含所有结果的数组。然后,删除其中不包含"(原声音乐)"answers"(下载相册)"的数组元素(除了第一个结果),这样最终的数组看起来像:

[0] => "Inception"
[1] => "Inception (soundtrack)"
[2] => "Inception (Download album)"

最好的方法是什么?感谢

解码JSON

$json = json_decode($wikisearchlist);
$results = $json[1];

筛选数组

$first = array_shift($results);
$filtered = array_filter($results, function($result) {
    return strpos($result, '(soundtrack)') !== false
        || strpos($result, '(Download album)') !== false;
});
array_unshift($filtered, $first);

此处演示-http://codepad.viper-7.com/siX4aY