【问题标题】:Group array by number of characters [duplicate]按字符数对数组进行分组[重复]
【发布时间】:2013-08-24 20:19:04
【问题描述】:

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

$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")
);

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    这样做可能最简单:

    $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);
    

    【讨论】:

      【解决方案2】:
      $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);
      

      【讨论】:

        猜你喜欢
        • 2020-06-06
        • 1970-01-01
        • 2022-01-14
        • 2021-10-05
        • 2014-11-28
        • 1970-01-01
        • 2017-07-25
        • 2015-02-21
        • 1970-01-01
        相关资源
        最近更新 更多