我想计算此数组中字符串中最后一个字符之前字符 t 的所有值(城市名称)。
ARRAY
$cities_array = array(
"city1" => "Paris_t1",
"city2" => "Madrid_t1",
"city3" => "Amsterdam_t1",
"city4" => "London_i1",
"city5" => "Miami_i1",
"city6" => "Berlin_i1",
"city7" => "Brussels_i1",
"city8" => "Toronto_i1",
);
结果应为: 3 (Paris_t1 - Madrid_t1 - Amsterdam_t1)
我相信我必须结合起来:
array_count_values($cities_array)
和
substr($value, -2, 1) == "t"
我试过,但我只得到错误。
答案 0 :(得分:2)
这会给你你想要的东西。
$cities_array = array(
"city1" => "Paris_t1",
"city2" => "Madrid_t1",
"city3" => "Amsterdam_t1",
"city4" => "London_i1",
"city5" => "Miami_i1",
"city6" => "Berlin_i1",
"city7" => "Brussels_i1",
"city8" => "Toronto_i1",
);
$count = 0;
$city_text = '';
foreach($cities_array as $city){
if(substr($city, -2, 1) == "t"){
$count++;
$city_text .= $city . '-';
}
}
echo $count. "(".rtrim($city_text,'-').")";
答案 1 :(得分:0)
尝试以下解决方案:
$cities_array = array(
"city1" => "Paris_t1",
"city2" => "Madrid_t1",
"city3" => "Amsterdam_t1",
"city4" => "London_i1",
"city5" => "Miami_i1",
"city6" => "Berlin_i1",
"city7" => "Brussels_i1",
"city8" => "Toronto_i1",
);
$filtered_array = array_filter($cities_array, function($val){
return (strpos($val, 't', (strlen($val)-2)) !== false);
});
print_r($filtered_array);
输出 - (你可以通过以下方式内爆数组来获得所需的结果)
Array
(
[city1] => Paris_t1
[city2] => Madrid_t1
[city3] => Amsterdam_t1
)
在strpos
第三个参数strlen($val)-2)
的上述解决方案中,即将从$val
的第二个字符