简体   繁体   English

PHP Array:按字符串的一部分分组

[英]PHP Array: Group by portion of a string

I have an array containing the strings below我有一个包含以下字符串的数组

'Proxima Nova Bold'
'Proxima Nova Italic'
'Proxima Nova Regular'
'Skolar Bold'
'Skolar Italic'
'Skolar Regular'
'Consolas'

i'd like to have an output like我想要一个输出

'Proxima' 
'Skolar' 
'Consolas'

essentially grouping by the parent/master name...is it possible in PHP?基本上按父/主名称分组......在PHP中可能吗?

Explode each string into words, return the first word, and then use array_unique to remove the duplicates.将每个字符串分解为单词,返回第一个单词,然后使用array_unique删除重复项。

array_unique(array_map(function($str) {
    $words = explode(' ', $str);
    return $words[0];
}, $array));

This should be the easiest way to do it:这应该是最简单的方法:

//Create an empty array
$new_array = array();
foreach($array as $value) {
  //Explode the text into a new array, separated by space
  $first_part = explode(" ", $value);
  //Push the first word into the new array
  array_push($new_array, $first_part[0]);
}
//Now get only unique values
print_r(array_unique($new_array));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM