php重构数组

时间:2011-05-20 22:54:57

标签: php

鉴于我的数组

array [0]
    fielda: cca
    fieldb: my value b
    fieldc: my value c
    fieldd: my value d

array [1]
    fielda: cca
    fieldb: my value b
    fieldc: my value c
    fieldd: my value d

array [2]
    fielda: cca
    fieldb: my value b
    fieldc: my value c
    fieldd: my value d

array [3]
    fielda: ccb
    fieldb: my value b
    fieldc: my value c
    fieldd: my value d

array [4]
    fielda: ccb
    fieldb: my value b
    fieldc: my value c
    fieldd: my value d

是否有一种简单的方法可以对其进行重组,以便将fielda分组为

array [0]
    fielda: cca
        array [0]
            fieldb: my value b
            fieldc: my value c
            fieldd: my value d
        array [1]           
            fieldb: my value b
            fieldc: my value c
            fieldd: my value d
        array [2]                   
            fieldb: my value b
            fieldc: my value c
            fieldd: my value d
        array [3]                   

array [1]
    fielda: ccb
        array [0]
            fieldb: my value b
            fieldc: my value c
            fieldd: my value d
        array [1]           
            fieldb: my value b
            fieldc: my value c
            fieldd: my value d

2 个答案:

答案 0 :(得分:2)

也许有一种更简单的方法,但这应该适合你:

$new_array = array();
foreach ($array as $values) // $array is your original array
{
    $new_array[array_shift($values)][] = $values;
}
print_r($new_array);

DEMO:http://codepad.org/M26yBLL4

答案 1 :(得分:2)

这样的事情应该有效:

$ restructured = array();

foreach( $myarray as $value ){
    $key = $value['fielda'];
    unset($value['fielda'];
    $restructured[$key][] = $value;
}

Fyi:我正在通过手机回复 - 请原谅任何错别字/自相关等...