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 格式打印它?

IE:

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

2 回答 2

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);
于 2013-08-24T20:20:31.997 回答
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);
于 2013-08-24T20:31:35.860 回答