我想搜索一个数组,例如" new" "纽约" "其他" "东西&#34 ;, 并且只组合构成一个州的话语的那些。
在这个例子中,我希望将状态匹配组合在数组中:
由此:
<?php
$states = array("new york", "Nevada");
$names = array("something", "green", "something", "yellow", "new", "york", "new","jersey");
对此:
$names = ( "something", "green", "something", "yellow", "new york", "new jersey");
因此改变名称数组以组合状态。
答案 0 :(得分:1)
在查看解决方案之前,请先看看两个假设: 1.以$ names检查并发数组元素。 2.检查$ States。
$states = array("new york", "Nevada");
$names = array("something", "green", "something", "yellow", "new", "york", "new","jersey");
foreach($names as $k => $v) {
$combined_names = $names[$k]." ".$names[$k+1];
if (in_array($combined_names, $states)) {
$names[] = $combined_names;
$names[$k] = $names[$k+1] = '';
}
}
$result = array_values(array_filter($names));
输出:
Array
(
[0] => something
[1] => green
[2] => something
[3] => yellow
[4] => new
[5] => jersey
[6] => new york
)
答案 1 :(得分:0)
假设您可以在注释中解决“新泽西”问题,以下内容会将一个单词数组映射到目标数组(在本例中为状态)。然后对生成的数组进行重复数据删除并重新编制索引。
如果名称只需匹配目标字符串中的整个单词,stripos
测试可以更改为更高级的preg_match
;
<?php
$states = array("new york", "Nevada");
$names = array("something", "green", "something", "yellow", "new", "york", "new","jersey");
$result = array_map(function ($e) use ($states) {
foreach ($states as $state) {
// The moment a match is found, return it
if (stripos($state, $e) !== false)
{
return $state;
}
}
// If no match was found, fall back to the word in the original array
return $e;
}, $names);
print_r(array_values(array_unique($result)));
=
Array
(
[0] => something
[1] => green
[2] => yellow
[3] => new york
[4] => jersey
)