2

どうやってするの。たとえば、配列があります。

array(
    0 => 'Regular 1 000',
    1 => 'Regular 500',
    2 => 'Regular 2 000',
    3 => 'Big',
    4 => 'Regular 1 000 000',
    5 => 'Regular 50 000'
)

私はそれらをこの順序で配置する必要があります:

array(
    3 => 'Big',
    1 => 'Regular 500',
    0 => 'Regular 1 000',
    2 => 'Regular 2 000',
    5 => 'Regular 50 000',
    4 => 'Regular 1 000 000'
 )

そして、インデックスの関連付けを維持する必要があります。使用する必要があるようuasortです。誰かが私に callable ( $cmp_function )値に使用する関数を提案できますか?

4

2 に答える 2

6

これは配列の数値部分でのみ機能しますが、アルファベット順の並べ替えのために配列をジャグリングすることに頭を悩ませようとしています。誰かが追加できる場合は、これを更新してください。これは頭​​痛
の種 だったので、可能であればフォーマットを変更してみてください。

$x = array(
    'Regular 1 000',
    'Regular 500',
    'Regular 2 000',
    'Big',
    'Regular 1 000 000',
    'Regular 50 000'
);

与える:

編集:ユーレカ!

$x = array(
    'A 100', // extra for testing
    'Regular 1 000',
    'Regular 500',
    'Regular 2 000',
    'Big',
    'Regular 1 000 000',
    'Regular 50 000'
);

function cus_sort($a, $b) { // you can also just do $x = function ($a, $b) {}
    $tmp_a = array(); $tmp_b = array(); // temp storage
    $tmp_a = explode(" ", $a, 2);
    if (@$tmp_a[1]) { // tmp_a exists (suppress invalid offset error if not)
        $a_numeric = (int)preg_replace("/[^0-9]/", '', $tmp_a[1]);
        // remove all non-numerical (...should add hyphens if needed...)
    } else {
        $a_numeric = false; // text only.
    }
    // else make sure that it evaluates false when we check.
    $tmp_b = explode(" ", $b, 2); // split into maximum 2 parts at first space.
    if (@$tmp_b[1]) { // tmp_b exists (suppress invalid offset error if not)
        $b_numeric = (int)preg_replace("/[^0-9]/", '', $tmp_b[1]);
    } else {
        $b_numeric = false; 
    }
    // onwards to sorting
    if ($tmp_a[0] == $tmp_b[0]) { //alphabetical parts are the same.
    // numerical sort
        if (($a_numeric > $b_numeric) || (!$b_numeric)) {
            return 1;
        } elseif (($a_numeric < $b_numeric) || (!$a_numeric)) {
            return -1;
        } else {
            return 0;
        }
    } else {
        // alpha sort
        $compare = strcasecmp($tmp_a[0], $tmp_b[0]);
        // see note below
        if ($compare > 0) {
            return 1;
        } elseif ($compare < 0) {
            return -1;
        } else {
            return 0;
        }
    }
}

uasort($x, "cus_sort");

注:大文字strcasecmp(string $a, string $b)小文字を区別しない数値で、順番にチェックする方法です。

print_r戻り値:

Array
(
    [0] => A 100
    [4] => Big
    [2] => Regular 500
    [1] => Regular 1 000
    [3] => Regular 2 000
    [6] => Regular 50 000
    [5] => Regular 1 000 000
)
于 2012-09-28T14:39:52.967 に答える
2

このコードを試してください

$sorted_arr = array_map(
  function ($str) {
    preg_match('/[a-zA-Z]*\s*((\d+\s*)*)/', $str, $matches);
    return (int) str_replace(' ', '', $matches[1]);
  }, $arr
);
asort($sorted_arr, SORT_NUMERIC);
foreach ($sorted_arr as $key=>$value)
  $sorted_arr[$key] = $arr[$key];
print_r($sorted_arr);
于 2012-09-28T14:47:49.263 に答える