Группировать массив по ключу

У меня есть массив:

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

Помогите мне, как я могу сгруппировать массив?

1

Решение

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

)
0

По вопросам рекламы [email protected]