我有3个不同的数组
$partylist = ['party1','party2','party3'];
$position = ['position1','position2'];
$members= ['name1','name2','name3','name4','name5','name6'];
我想在每个$ partylist数组值中嵌套$ position和$ member,但是在php语法中将$ position作为关联名称并将$ members作为值嵌套。
array {
party1 {
array{
position1 => name1
position2 => name2
}
}
party2 {
array{
position1 => name3
position2 => name4
}
}
party3 {
array{
position1 => name5
position2 => name6
}
}
}
答案 0 :(得分:0)
以@Alive为死的答案,如果嵌套第二个foreach()
,则可以动态增加/减少聚会,职位或会员号码
//use count($position) to divide the members
$partymembers = array_chunk($members,count($position));
// create new array
$partyArray=[];
foreach($partylist as $key1 => $party){
// create the party key
$partyArray[$party] = [];
foreach($position as $key2 => $p){
// create the party position key and member
$partyArray[$party][$p] = isset($partymembers[$key1][$key2]) ? $partymembers[$key1][$key2] : '';
}
}
答案 1 :(得分:0)
<?php
$partylist = ['party1','party2','party3'];
$position = ['position1','position2'];
$members = ['name1','name2','name3','name4','name5','name6'];
$out = [];
foreach ($members as $member) {
if (!empty($out) && !next($position)) {
reset($position);
if(!next($partylist)) {
die('Not enough parties.'.PHP_EOL);
}
}
$out[current($partylist)][current($position)] = $member;
}
print_r($out);