简体   繁体   English

如何按元素长度将PHP数组分组?

[英]How to group a PHP array by its elements length?

I have an array like:- 我有一个像这样的数组:

array("a","b","ab","xy","abc","xyz","abcd","abcde");

I want to group this array by value's length. 我想按值的长度将此数组分组。 So it should be like:- 所以应该像:

  array(
    "1" => array("a","b"), //because there are two value which their lengths are = 1
    "2" => array("ab","xy"),
    "3" => array("abc","xyz"),
    "4" => array("abcd"),
    "5" => array("abcde")
  );

Than I want to reverse order by index; 比我想按索引颠倒顺序;

Final output should; 最终输出应;

array(
  "13" => array("13 length char"),
  "12" => array("12 length char"),
  ...
  ...
  "5" => array("abcde"),
  "4" => array("abcd"),
  "3" => array("abc","xyz"),
  "2" => array("ab","xy"),
  "1" => array("a","b")
);

After I used krsort() output is 在我使用krsort()输出是

Array(
[10] => Array
    (
        [0] => Abdülbari
    )

[8] => Array
    (
        [0] => ablefari
    )

[7] => Array
    (
        [0] => arakari
    )

[3] => Array
    (
        [0] => ari
    )

[14] => Array
    (
        [0] => ağari beğari
    )

[20] => Array
    (
        [0] => ağır erkeli muzari
    )

[12] => Array
    (
        [0] => Amerikanvari
        [1] => amudufıkari
    )

[5] => Array
    (
        [0] => abari
        [1] => abari
        [2] => Acari
        [3] => apari
        [4] => atari
    )

[6] => Array
    (
        [0] => abbari
        [1] => antari
        [2] => asgari
        [3] => asgari
        [4] => aşari
    )

 )

Array index should ordered from bigger index to lower index like: 20,14,12.. 数组索引应从较大的索引到较低的索引排序,例如:20、14、12。

You can do this, quite easily, with a combination of mb_strlen() , foreach() loop, and a temporary array in which you use the length as the key. 可以结合使用mb_strlen()foreach()循环和一个使用长度作为键的临时数组来轻松地做到这一点。

Now, I'm not going to write out the code for you, as this strikes me very similar to a homework/test project. 现在,我不会为您编写代码,因为这让我觉得与作业/测试项目非常相似。 But if you take a look at the following links, they should help you get started: 但是,如果您查看以下链接,它们应该可以帮助您入门:

http://php.net/manual/en/function.mb-strlen.php http://php.net/manual/zh/function.mb-strlen.php
http://php.net/manual/en/control-structures.foreach.php http://php.net/manual/en/control-structures.foreach.php

Edit, added: 编辑,添加:

Seeing as there have been a couple of answers already posting the code, I don't see any further harm coming from posting one myself. 看到已经有两个答案已经发布了代码,我看不到自己发布一个代码会带来更多的危害。

/**
 * Groups the values based upon their length, and returns
 * an array sorted by descending order of length.
 * 
 * Note: This expects the values to be encoded with UTF-8.
 * 
 * @param array $array
 * @return array
 */
function group_values ($array) {
    // Create the temp variable to hold the sorted values.
    $tmp = array ();

    foreach ($array as $elm) {
        // First we need the length of the string, to use as the index for the grouping.
        $len = mb_strlen ($elm, 'UTF-8');

        // Add the element to the temp array, as a new element for the index key.
        $tmp[$len][] = $elm;
    }

    // Sort the array in reverse order, forcing a numerically comparison.
    krsort ($tmp, SORT_NUMERIC);

    // Return the finished array.
    return $tmp;
}

Or maybe just walk the array with a function that checks the length of a given value and assigns it to a group. 或者,也许只是使用检查给定值长度并将其分配给组的函数遍历数组。

<?php
    $arr = [ 'a','b','ab','xy','abc','xyz','abcd','abcde' ];
    $groups = [];

    array_walk( $arr, function( &$value, $key ) use (&$groups) {
        $groups[ mb_strlen( $value ) ][] = $value;
    });
?>

You can see the running example https://eval.in/671158 您可以看到正在运行的示例https://eval.in/671158

Note you need at least PHP 5.3 to be able to inherit scope, with use keyword. 注意,至少需要PHP 5.3才能use关键字继承范围。

Also, there's no point in reversing the array. 另外,反转数组没有任何意义。 When you iterate as follows: 当您进行以下迭代时:

$count = count( $groups );
for ( $i = $count; $i >= 0; --$i )
    print_r( $groups[ $count - $i ] );

And you are printing them as ordered as well. 您也将按订单打印它们。 Again, no need to abuse php functions just because they seem easier to write in. 同样,无需仅仅因为看起来容易编写而就滥用php函数。

You can do it like below:- 您可以像下面这样:

<?php

$array = array("a","b","ab","xy","abc","xyz","abcd","abcde");

$final_array = array();
foreach ($array as $arr){
   $final_array[strlen( $arr)][] =  $arr;  //I have checked the  length of values and make it the key so that automatically your each value will go to corresponding length array
}

echo "<pre/>";print_r($final_array);

Output:- https://eval.in/671126 输出: -https : //eval.in/671126

Note:- I have checked the length of values and make it the key so that automatically your each value will go to corresponding length array 注意:-我已经检查了值的长度并将其作为键,以便您的每个值自动进入相应的长度数组

final output what you want:- https://eval.in/671137 最终输出你想要什么: -https : //eval.in/671137

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

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