我有一个从db返回的数组:
[0] array(2) {
["Brand"] "A"
["Family"] "B"
}
[1] array(2) {
["Brand"] "A"
["Family"] "C"
}
[2] array(2) {
["Brand"] "A"
["Family"] "D"
}
[3] array(2) {
["Brand"] "B"
["Family"] "ABC"
}
[4] array(2) {
["Brand"] "B"
["Family"] "DD"
}
我需要像这样创建一个数组:
[0] array(2) {
["Brand"] "A" array() {
"B",
"C",
"D"
}
[1] array(2) {
["Brand"] "B" array() {
"ABC",
"DD"
}
所以基本上,品牌应该是独一无二的,在每个品牌中我需要一个家庭列表。
答案 0 :(得分:2)
尝试以下操作,$mainarray
是您现在拥有的数组
$brand = array();
foreach($mainarray as $v){
$brand['Brand'][$v['Brand']][] = $v['Family'];
}
答案 1 :(得分:0)
这是一个简单的数组递归练习。
这里有一些PHP伪代码:
$output = array();
foreach($array as $i){
//loop through the array returned from the db
$output[$i["brand"]] = array_unique(array_merge($output[$i["brand"]], array($i["Family"])));
//merge the existing families for the brand with the current iteration's, and maintain a set datastructure (no duplicate entries for each family)
}
var_dump($output);
答案 2 :(得分:0)
这是你所需要的:
<?php
$array1=array(array('Brand'=>'A','Family'=>'B'), array('Brand'=>'A','Family'=>'C'), array('Brand'=>'A','Family'=>'D'), array('Brand'=>'B','Family'=>'ABC'), array('Brand'=>'B','Family'=>'DD'));
$brand=array();
foreach($array1 as $value=>$data){
foreach($data as $value2=>$data2){
if($value2=='Family'):
if($value<3):
$brand['Brand']['A'][]=$data2;
else:
$brand['Brand']['B'][]=$data2;
endif;
endif;
}
}
echo "<pre>";
print_r($brand);
echo "</pre>";
?>