将单个数组转换为多维数组

时间:2014-03-11 12:14:00

标签: php arrays

如何创建多维数组

Array(
[0] => Array
    (
        [id] => 1
        [cat] => category 1
        [sub] => sub 1
    )

[1] => Array
    (
        [id] => 2
        [cat] => category 1
        [sub] => sub 2
    )

[2] => Array
    (
        [id] => 3
        [cat] => category 1
        [sub] => sub 1
    )

[3] => Array
    (
        [id] => 4
        [cat] => category 2
        [sub] => sub 3
    )

[4] => Array
    (
        [id] => 5
        [cat] => category 2
        [sub] => sub 2
    )

[5] => Array
    (
        [id] => 6
        [cat] => category 1
        [sub] => sub 1
    )

)

我需要

Array(
[category 1] => Array
    (
        [0] => sub 1
        [1] => sub 2
    )

[category 2] => Array
    (
        [0] => sub 2
        [1] => sub 3
    )

)

3 个答案:

答案 0 :(得分:0)

$new = array_reduce(
    $original,
    function ($return, $item) {
        if(array_search($item['sub'], (array)$return[$item['cat']]) === false) {
            $return[$item['cat']][] = $item['sub'];
        }
        return $return;
    }
);

答案 1 :(得分:0)

尝试:

$newarray = array();

foreach($array as $k=>$v){
    $key = $v['cat'];
    if(isset($newarray[$key])){
        if(!in_array($v['sub'],$newarray[$key])){
            $newarray[$key][] = $v['sub'];
        }
    }
    else
    {
        $newarray[$key][] = $v['sub'];
    }

}

print_r($newarray);

<强> Demo

逻辑简单,如:

  1. 获取类别
  2. 检查新阵列中是否存在类别

    a)如果存在:检查子是否已经存在,如果没有插入
    b)如果类别不存在:插入类别和子

答案 2 :(得分:0)

for($i=0;$i<10;$i++){
$i2 = $i+1;
$arr[$i][id] = "$i2";
$arr[$i][cat] = 'category '.$i2;
$arr[$i][sub] = 'sub '.$i2;
}

                $file_post = $arr;
                $file_count = count($arr);      
                for ($i=0; $i<$file_count; $i++) {
                        $k=0;
                        foreach ($arr[$i] as $key) {
                                $arr2['category ' . $i][$k] = $key;
                                $k++;
                        }
                }


print_r($arr2);

试试这个, 首先,我创建了给定的simble数组