PHP array combination with Left to Right order [duplicate]

一曲冷凌霜 提交于 2019-12-12 02:46:25

问题


I have a PHP array that looks like this

$alphabet= array('a','b','c')

$alphabet is a input i need a result like $result

Expected output:

$result= array(
  [0]=> "a"
  [1]=> "b"
  [2]=> "c"
  [3]=> "ab"
  [4]=> "ac"
  [5]=> "bc"
  [6]=> "abc"
)

Note: here, I would not like sorting to use. Thanks!


回答1:


Use usort and costum sort function:

$array = array("a", "bc", "bb", "aa", "cc", "bb");

function sortByValueLength($a, $b)
{
    $aLength = mb_strlen($a, 'utf-8');
    $bLength = mb_strlen($b, 'utf-8');
    if ($aLength == $bLength) {
        return strcmp($a, $b);
    }

    return $aLength - $bLength;
}

usort($array, 'sortByValueLength');

var_export($array);

Example result here



来源:https://stackoverflow.com/questions/30368260/php-array-combination-with-left-to-right-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!