转换多维数组

时间:2016-02-19 00:39:22

标签: php arrays

作为构建一些json从而构建依赖下拉列表的踏脚石,我想转换这个数组......

Array
(
    [0] => Array
        (
            [id] => 4
            [project_id] => 2289
            [task] => Drawing
        )

    [1] => Array
        (
            [id] => 5
            [project_id] => 2289
            [task] => Surveying
        )

    [2] => Array
        (
            [id] => 6
            [project_id] => 2289
            [task] => Meeting
        )

    [3] => Array
        (
            [id] => 1
            [project_id] => 2282
            [task] => Folding
        )

    [4] => Array
        (
            [id] => 2
            [project_id] => 2282
            [task] => Printing
        )

    [5] => Array
        (
            [id] => 3
            [project_id] => 2282
            [task] => Cutting
        )

)

..对于这样的事情......

Array
(
  [0] = Array
        (
        [project_id] => 2289
        [task] => Array
                  (
                  [0] => Drawing
                  [1] => Surveying
                  [2] => Meeting
                  )
        )
  [1] = Array
        (    
        [project_id] => 2282
        [task] => Array
                  (
                  [0] => Folding
                  [1] => Printing
                  [2] => Cutting
                  )
        )

)

使用...

$newArray = array();
foreach ($array as $row)
{
   $newArray[$row['project_id']][] = $row['task'];
}

......我能够得到这个......

Array
(
    [2289] => Array
        (
            [0] => Drawing
            [1] => Surveying
            [2] => Meeting
        )

    [2282] => Array
        (
            [0] => Folding
            [1] => Printing
            [2] => Cutting
        )

)

...但我忘记了如何在结果中包含关联键

2 个答案:

答案 0 :(得分:1)

您只需使用索引修改foreach

$newArray = array();
$index = array();
foreach ($array as $row)
{
    $found = array_search( $row['project_id'], $index );
    if( $found === False )
    {
        $found = array_push( $newArray, array( 'project_id' => $row['project_id'] ) )-1;
        $index[$found] = $row['project_id'];
    }
    $newArray[ $found ]['task'][] = $row['task'];
}

eval.in demo

当找到新的project_id键时,它会被添加到$index数组中,所以 - 在下一个循环中搜索它 - 我可以检索相应多维数组的索引。

答案 1 :(得分:0)

只需按照您的意愿分配,project id在索引中,task不断推送它们:

$newArray = array();
foreach ($array as $row) {
   $newArray[$row['project_id']]['project_id'] = $row['project_id'];
   $newArray[$row['project_id']]['task'][] = $row['task'];
}
$newArray = array_values($newArray); // reindex
// removes `$row['project_id']` on each group

注意:只需使用array_values重置您在project id分组中使用的分组键。