在php中更改数组的结构

时间:2013-08-22 00:25:17

标签: php arrays multidimensional-array

我是编程新手,并且负责更改数组的结构,我无法让它工作。

这是原始数组:

[0] => Array
    (
        [att_values_id] => 5
        [att_value] => Sloping
        [att_id] => 5
        [att_category] => Frame
    )

[1] => Array
    (
        [att_values_id] => 13
        [att_value] => Time Trial
        [att_id] => 5
        [att_category] => Frame
    )

[2] => Array
    (
        [att_values_id] => 21
        [att_value] => Mountain
        [att_id] => 5
        [att_category] => Frame
    )

[3] => Array
    (
        [att_values_id] => 15
        [att_value] => Carbon
        [att_id] => 3
        [att_category] => Material
    )

[4] => Array
    (
        [att_values_id] => 15
        [att_value] => Titanium
        [att_id] => 9
        [att_category] => Frame
    )

[5] => Array
    (
        [att_values_id] => 15
        [att_value] => Aluminum
        [att_id] => 17
        [att_category] => Frame
    )

[6] => Array
    (
        [att_values_id] => 7
        [att_value] => Expensive
        [att_id] => 12
        [att_category] => Price
    )

[7] => Array
    (
        [att_values_id] => 7
        [att_value] => Moderate
        [att_id] => 33
        [att_category] => Price
    )

[8] => Array
    (
        [att_values_id] => 7
        [att_value] => Entry Level
        [att_id] => 40
        [att_category] => Price
    )

我必须改为:

Array
   (
       [Frame] => Array
           (
                [5] => Sloping
                [13] => Mountain
                [21] => Time Trial
            )
       [Material] => Array
           (
                [3] => Carbon
                [9] => Titanium
                [17] => Aluminum
            )
       [Price] => Array
           (
                [12] => Expensive
                [33] => Moderate
                [40] => Entry Level
            )
      )

我尝试使用foreach来完成数组,但我不知道如何构建新数组。

1 个答案:

答案 0 :(得分:0)

这个小伪代码是我们在明确做作业之前最接近的。

foreach (firstarray as key => value) {
 newarray[value['att_category']][value['att_id']]=value['att_value'];
}