PHP-PHP如何生成多维数组

PHP-PHP如何生成多维数组

想挽留 发布于 2017-01-02 字数 420 浏览 1172 回复 2

有这么个需求:
原始数据:

$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"),
);

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

想挽留 2017-10-31 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) );

清晨说ぺ晚安 2017-02-17 1 楼

,终于弄明白题意了,折腾了好久,终于纠结出来一个方法,未使用数组的引用,借助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));
?>