按字符数组数组

时间:2013-08-24 20:19:04

标签: php arrays

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

$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 个答案:

答案 0 :(得分: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 :(得分: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);