PHP-PHP如何生成多维数组
有这么个需求:
原始数据:
$rows = array(
array("id"=>1, "type"=>1, "value"=>"a"),
array("id"=>2, "type"=>1, "value"=>"b"),
array("id"=>3, "type"=>1, "value"=>"c"),
array("id"=>4, "type"=>2, "value"=>"d"),
array("id"=>5, "type"=>2, "value"=>"e"),
array("id"=>6, "type"=>2, "value"=>"f"),
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你是要这样的不:
function makemultiarr($rows=array(),$keys=array())
{
$result = array();
$num = count($keys)-1;
foreach($rows as $row)
{
$arr = &$result;
/*根据keys循环多维值到$result中*/
foreach($keys as $k => $v)
{
if( !isset($arr[$row[$v]]) && $k<$num) $arr[$row[$v]] = array();
if( !isset($arr[$row[$v]]) && $k==$num) $arr[$row[$v]] = $row;
$arr = &$arr[$row[$v]];
}
}
return $result;
}
$rows = array(
array("id"=>1, "type"=>1, "value"=>"a"),
array("id"=>2, "type"=>1, "value"=>"b"),
array("id"=>3, "type"=>1, "value"=>"c"),
array("id"=>4, "type"=>2, "value"=>"d"),
array("id"=>5, "type"=>2, "value"=>"e"),
array("id"=>6, "type"=>2, "value"=>"f"),
);
$keys = array("type", "id");
print_r(makemultiarr($rows,$keys) );
,终于弄明白题意了,折腾了好久,终于纠结出来一个方法,未使用数组的引用,借助json_encode方法和array_merge_recursive实现的一个版本
<?php
$rows = array(
array("id"=>1, "type"=>1, "value"=>"a"),
array("id"=>2, "type"=>1, "value"=>"b"),
array("id"=>3, "type"=>1, "value"=>"c"),
array("id"=>4, "type"=>2, "value"=>"d"),
array("id"=>5, "type"=>2, "value"=>"e"),
array("id"=>6, "type"=>2, "value"=>"f"),
);
$keys = array("id","type");
function groupByKeys($rows,$keys,$ext='_') {
$res = array();
foreach($rows as $row) {
$tmp = $row;
foreach($keys as $k) {
//为了利用array_merge_recursive方法的特性,使用非数字的键
$tmp = array($k.$ext.$row[$k] => $tmp);
}
$res = array_merge_recursive($res,$tmp);
}
$replace_keys = array();
foreach($keys as $k) {
$replace_keys[] = $k.$ext;
}
$str = str_replace($replace_keys,'',json_encode($res));
return json_decode($str,true);
}
print_r(groupByKeys($rows,$keys));
?>