将属性中的项目(或具有属性)中的项目分配给属性后的另一个存储桶(或数组)...
我有一个类似
的数组 Array
(
[type1] => Array
(
[0] => 1,
[1] => 2,
[2] => 3,
[3] => 4
)
[type2] => Array
(
[0] => 5,
[1] => 6,
[2] => 7,
[3] => 8
)
[type3] => Array
(
[0] => 9,
[1] => 10,
[2] => 11,
[3] => 12
)
[type4] => Array
(
[0] => 13,
[1] => 14,
[2] => 15,
[3] => 16
)
)
所以我需要将它排序成一个数组,这样这个新数组的每个元素都将所有类型的元素均等地分配给新数组的每个元素
我需要什么
array(
[0]=>array(1,5,9,13)
[1]=>array(2,6,10,14)
[2]=>array(3,7,11,15)
[3]=>array(4,8,12,16)
)
这里的问题是第一个数组的子数组可能有不同的元素
更简单的版本:想象一下,你有一组来自不同国家的马匹 你如何组织一个“n”(这里是4个)不同种族的数量,以便在所有种族中,所存在的马的国家尽可能均匀分布
在Db中就像是
regid nation race1
1 country1 1
2 country2 1
3 country3 0
4 country1 1
5 country1 1
其中regid是每个参与者的id no,而race1是表示其是否参加该种族
答案 0 :(得分:1)
以下内容生成两个数组:$values
包含值,$out
包含type1:3
形式的键。变量$max
确定最大集合数:
$arr['type1'] = array(1, 2, 3, 4, 5);
$arr['type2'] = array(6, 7, 8, 9);
$arr['type3'] = array(10, 11, 12, 13, 14, 15);
$arr['type4'] = array(16, 17, 18, 19);
$arr['type5'] = array(20, 21, 22, 23, 24);
$max = 5;
$out = array();
$values = array();
$i = 0;
foreach ($arr as $key1 => $type){
foreach ($type as $key2 => $item){
$out[$i%$max][] = $key1.':'.$key2;
$values[$i%$max][] = $item;
$i++;
}
}
var_dump($values);
[0] => array(1, 6, 11, 16, 21)
[1] => array(2, 7, 12, 17, 22)
[2] => array(3, 8, 13, 18, 23)
[3] => array(4, 9, 14, 19, 24)
[4] => array(5, 10, 15, 20)
或者您可以访问数组键:
var_dump($out);
Array
(
[0] => Array
(
[0] => type1:0
[1] => type2:0
[2] => type3:1
[3] => type4:0
[4] => type5:1
)
[1] => Array
(
[0] => type1:1
[1] => type2:1
[2] => type3:2
[3] => type4:1
[4] => type5:2
)
[2] => Array
(
[0] => type1:2
[1] => type2:2
[2] => type3:3
[3] => type4:2
[4] => type5:3
)
[3] => Array
(
[0] => type1:3
[1] => type2:3
[2] => type3:4
[3] => type4:3
[4] => type5:4
)
[4] => Array
(
[0] => type1:4
[1] => type3:0
[2] => type3:5
[3] => type5:0
)
)