我有这样一个数组:
$data=array(
array('id'=>12,'name'=>'box1','color'=>'red','content_id'=>18,'content'=>'roses'),
array('id'=>12,'name'=>'box1','color'=>'red','content_id'=>22,'content'=>'daisies'),
array('id'=>38,'name'=>'box2','color'=>'green','content_id'=>22,'content'=>'daisies'),
);
我想把它转换成这样的结构:
$structure = array('id'=>
array('name','color','content_id'=>array(
'content')));
就变成了
array(
'12'=>array('name'=>'box1','color'=>'red','content_id'=>array(
'18'=>'roses',
'22'=>'daisies')),
'38'=>array('name'=>'box2','color'=>'green','content_id'=>array(
'22'=>'daisies'))
);
我创建了一个函数,用于单个$data数组(即x_array($data[0],$structure)):
function x_array($data,$struc,$first=true)
{
foreach ($struc as $struc_field=>$inner_struc)
{
if (!is_array($inner_struc))
{$result[$inner_struc]=$data[$inner_struc];}
else {
$res=x_array($data,$inner_struc,false);
//ignore the first field name and use it's value as key instead
if ($first) {$result[$data[$struc_field]]=$res;}
else {$result[$struc_field][$data[$struc_field]]=$res;}
}
}
return $result;
}
查看:http://phpfiddle.org/main/code/y3e-wxh
然而,当涉及到集成多个数组的信息而不复制或覆盖信息时,我陷入了下一步该做什么。请注意,我发布了一个简化的数据和结构数组,最终的函数应该能够管理任何结构深度和任何数量/名称的字段。
试试这个:
$data=array(
array('id'=>12,'name'=>'box1','color'=>'red','content_id'=>18,'content'=>'roses'),
array('id'=>12,'name'=>'box1','color'=>'red','content_id'=>22,'content'=>'daisies'),
array('id'=>38,'name'=>'box2','color'=>'green','content_id'=>22,'content'=>'daisies'),
);
$res = array();
foreach($data as $key=>$val){
$res[$val['id']]['name'] = $val['name'];
$res[$val['id']]['color'] = $val['color'];
$res[$val['id']]['content_id'][$val['content_id']] = $val['content'];
}
echo "<pre>";
print_r($res);
输出:Array
(
[12] => Array
(
[name] => box1
[color] => red
[content_id] => Array
(
[18] => roses
[22] => daisies
)
)
[38] => Array
(
[name] => box2
[color] => green
[content_id] => Array
(
[22] => daisies
)
)
)