按键分组数组

时间:2014-11-16 07:53:49

标签: php arrays sorting grouping

我有一个数组:

array(
 "A1" => 4,
 "A2" =>5,
 "B1" => 2,
 "B2" =>7,
 "C1" => 4,
 "C2" =>5,
 "D1" => 4,
 "D2" =>5,
  .....
)

现在我只想要新的数组:

$arr1 = array("A"=>array("A1"=>4, "A2"=>5), "B" => array("B1" => 2, "B2" => "7"), ...)

$arr2 = array(
 0=>array("A1"=>"4","B1"=>2,"C1"=>4,"D1"=>4),
 1=>array("A2"=>"4","B2"=>2,"C2"=>4,"D2"=>4)
)

帮助我,我该如何对数组进行分组?

2 个答案:

答案 0 :(得分:0)

这应该适合你:

<?php

    $old = array(
                "A1" => 4,
                "A2" =>5,
                "B1" => 2,
                "B2" =>7,
                "C1" => 4,
                "C2" =>5,
                "D1" => 4,
                "D2" =>5,
            );

    $arr1 = array();
    $arr2 = array();

    foreach($old as $k => $v) {
        $arr1[substr($k, 0 ,1)][$k] = $v; 
        ksort($arr1);
        ksort($arr1[substr($k, 0 ,1)]);
    }

    foreach($old as $k => $v) {
        $arr2[substr($k, 1 ,2)-1][$k] = $v; 
        ksort($arr2[substr($k, 1 ,2)-1]);
    }


    print_r($arr1);
    print_r($arr2);

?>

输出:

//Array 1

Array
(
    [A] => Array
    (
        [A1] => 4
        [A2] => 5
    )

    [B] => Array
    (
        [B1] => 2
        [B2] => 7
    )

    [C] => Array
    (
        [C1] => 4
        [C2] => 5
    )

    [D] => Array
    (
        [D1] => 4
        [D2] => 5
    )

)

//Array2
Array
(
    [0] => Array
    (
        [A1] => 4
        [B1] => 2
        [C1] => 4 
        [D1] => 4
    )

    [1] => Array
    (
        [A2] => 5
        [B2] => 7
        [C2] => 5
        [D2] => 5
    )

)

答案 1 :(得分:0)

$arr = array(
 "A1" => 4,
 "A2" =>5,
 "B1" => 2,
 "B2" =>7,
 "C1" => 4,
 "C2" =>5,
 "D1" => 4,
 "D2" =>5,
);

ksort($arr, SORT_NATURAL);
$arr1 = $arr2 = array();
foreach ($arr as $key => $value) {
    $letter = substr($key, 0, 1);
    $index = (int)substr($key, 1) - 1;

    !isset($arr1[$letter]) && $arr1[$letter] = array();
    $arr1[$letter][$key] = $value;

    !isset($arr2[$index]) && $arr2[$index] = array();
    $arr2[$index][$key] = $value;
}

ksort($arr1, SORT_NATURAL);
ksort($arr2, SORT_NATURAL);

var_dump($arr1, $arr2);

输出:

array(4) {
  ["A"]=>
  array(2) {
    ["A1"]=>
    int(4)
    ["A2"]=>
    int(5)
  }
  ["B"]=>
  array(2) {
    ["B1"]=>
    int(2)
    ["B2"]=>
    int(7)
  }
  ["C"]=>
  array(2) {
    ["C1"]=>
    int(4)
    ["C2"]=>
    int(5)
  }
  ["D"]=>
  array(2) {
    ["D1"]=>
    int(4)
    ["D2"]=>
    int(5)
  }
}
array(2) {
  [0]=>
  array(4) {
    ["A1"]=>
    int(4)
    ["B1"]=>
    int(2)
    ["C1"]=>
    int(4)
    ["D1"]=>
    int(4)
  }
  [1]=>
  array(4) {
    ["A2"]=>
    int(5)
    ["B2"]=>
    int(7)
    ["C2"]=>
    int(5)
    ["D2"]=>
    int(5)
  }
}