Array_intersect和返回值的顺序



我是一个PHP新手,我有一个问题。

我试图使一个功能,添加标签的文本。我的函数工作,但返回的数组中标签的顺序是错误的。

请问如何更改订单

谢谢你的帮助。

<?php

$tags = [
'animals' => ['cat', 'dog', 'horse', 'ferret'],
'nature' => ['walk', 'outdoor', 'tree', 'plant']];


function getTags(string $text, array $tags): array
{
$lowerC = strtolower($text);
$str = preg_replace("/[^A-Za-z'- ]/", '', $lowerC);
$arrayT = explode(" ", $str);

$tagArray = [];
foreach ($tags as $tag => $value) {

if (array_intersect( $value, $arrayT )) {
$tagArray[] = $tag;
}

}   return $tagArray;

}


$res = getTags('During my walk, I met a white horse', $tags);
var_dump($res); // returns ['animals', 'nature'] but I'm trying to get ['nature', 'animals']

如果你想先得到'nature',因为'walk'在'horse'之前,你需要先遍历单词,而不是遍历标签。

$tags = [
'animals' => ['cat', 'dog', 'horse', 'ferret'],
'nature' => ['walk', 'outdoor', 'tree', 'plant'],
];


function getTags(string $text, array $tags): array
{
$lowerC = strtolower($text);
$str = preg_replace("/[^A-Za-z'- ]/", '', $lowerC);
$arrayT = explode(" ", $str);
$tagArray = [];
foreach ($arrayT as $word) {
// find tag for this word
foreach ($tags as $cat => $values) {
if (in_array($word, $values)) {
// append the tag to the list
$tagArray[] = $cat;
}
}
}

// remove duplicates
return array_unique($tagArray);

}

$res = getTags('During my walk, I met a white horse', $tags);
var_dump($res);

输出:

array(2) {
[0]=>
string(6) "nature"
[1]=>
string(7) "animals"
}

编辑

正如@GeorgeGarchagudashvili所提到的,可以通过准备一个数组进行比较来优化代码。这里有一个方法:

function getTags(string $text, array $tags): array
{
$lowerC = strtolower($text);
$str = preg_replace("/[^A-Za-z'- ]/", '', $lowerC);
$arrayT = explode(" ", $str);

// Prepare tags for searching
$searchTags = [];
foreach ($tags as $cat => $values) {
foreach ($values as $word) {
$searchTags[$word] = $cat;
}
}
$tagArray = [];
foreach ($arrayT as $word) 
{
// find tag for this word
if (isset($searchTags[$word])) 
{
// append the tag to the list
$tagArray[] = $searchTags[$word];
}
}

// remove duplicates
return array_unique($tagArray);

}

最新更新