有两个阵列说
1. Groups
$groups = array("user", "account", "client")
2. Results
$results = array(
0 => array(
"user" => "U1",
"account" => "A1",
"client" => "C1"
),
1 => array(
"user" => "U1",
"account" => "A2",
"client" => "C1"
),
0 => array(
"user" => "U1",
"account" => "A3",
"client" => "C1"
),
0 => array(
"user" => "U1",
"account" => "A2",
"client" => "C2"
),
0 => array(
"user" => "U1",
"account" => "A1",
"client" => "C4"
),
0 => array(
"user" => "U1",
"account" => "A1",
"client" => "C5"
),
0 => array(
"user" => "U1",
"account" => "A2",
"client" => "C5"
)
) ;
我想要关注OUTPUT
$output = array(
"U1" => array(
"A1" => array(C1,C4,C5),
"A2" => array(C1,C2,C5),
"A3" => array(C1)
)
);
Groups数组值是动态的,可以是任何顺序。我希望输出顺序,groups数组的第一个值是Output数组的父元素,group数组的第二个值是父Output数组的子元素,依此类推。
答案 0 :(得分:0)
只需像这样制作一个foreach循环
$new = array();
foreach($results as $key=>$value){
$new[$value["user"]][$value["account"]][] = $value["client"];
}
print_r($new);
使用$groups
:https://eval.in/857970
$new = array();
foreach($results as $key=>$value){
$new[$value[$groups[0]]][$value[$groups[1]]][] = $value[$groups[2]];
}
多个用户的示例:https://eval.in/857973
更新
对于动态组数组:如果您不在此处交互用户输入,则可以使用eval。 :https://eval.in/858306
答案 1 :(得分:0)
我希望您使用的PHP大于或等于5.6。我们有...
(splat operator)非常方便:
std::istream
这是working demo。
简而言之,我们利用array_map
的能力将任意数量的数组作为参数并且并行地遍历它们。