2013-08-24 50 views
0

以下代码将字符串放入数组中,并按每个元素中的字符数排序。按字符数组排列的组数

$str = 'audi toyota bmw ford mercedes dodge ...'; 

$exp = explode(" ", $str); 

usort($exp, function($a, $b){ 
    if (strlen($a) == strlen($b)) { 
    return 0; 
    } 
    return (strlen($a) < strlen($b)) ? -1 : 1; 
}); 

我该如何取这个一维数组,并按字符数将这些元素进行分组,并用索引指出字符数。在元素组中?

array(
[3] => array(bmw, ...) 
[4] => array(ford, audi, ...) 
[5] => array(dodge, ...) 
) 

有没有办法采取多维数组,并在一个PHP格式打印?

即:

$arr = array(
"3" => array("bmw"), 
"4" => array("audi"), 
"5" => array("dodge") 
); 

回答

2

这很可能是最容易做到这一点:

$exp = explode(" ",$str); 
$group = []; // or array() in older versions of PHP 
foreach($exp as $e) $group[strlen($e)][] = $e; 
ksort($exp); // sort by key, ie. length of words 
var_export($exp); 
1
$str = 'audi toyota bmw ford mercedes dodge'; 
$words = explode(" ", $str); // Split string into array by spaces 
$ordered = array(); 
foreach($words as $word) { // Loop through array of words 
    $length = strlen($word); // Use the character count as an array key 
    if ($ordered[$length]) { // If key exists add word to it 
     array_push($ordered[$length], $word); 
    } else { // If key doesn't exist create a new array and add word to it 
     $ordered[$length] = array($word); 
    } 
} 
ksort($ordered); // Sort the array keys 
print_r($ordered);