从具有不同值的相同键创建数组

时间:2014-04-30 18:16:21

标签: php arrays multidimensional-array

我需要在组合相同的键和放置时从数组中重新创建一个数组 在他们的价值观中......不清楚,这是一个具体的例子:

我有这个阵列1:

Array1
(
    [0] => Array
        (
            [profile_field_id] => 214
            [value] => 1
            [order] => 1
        )

    [1] => Array
        (
            [profile_field_id] => 214
            [value] => 2
            [order] => 2
        )

    [2] => Array
        (
            [profile_field_id] => 214
            [value] => 4
            [order] => 3
        )

    [3] => Array
        (
            [profile_field_id] => 214
            [value] => 8
            [order] => 4
        )

    [4] => Array
        (
            [profile_field_id] => 215
            [value] => 1
            [order] => 1
        )

    [5] => Array
        (
            [profile_field_id] => 215
            [value] => 2
            [order] => 2
        )

我需要从array1创建一个数组,输出应该是:

Array
(
    [214] => Array
        (

            [value] => Array
            (
             [1]
             [2]
             [4]
             [8]

            )

        )

    [215] => Array
        (
            [value] => Array
            (
             [1]
             [2]


            )
        )

感谢您的帮助, 杰斯

1 个答案:

答案 0 :(得分:1)

我认为这就是你要找的东西:

$array2 = array();                                                                  
foreach($array1 as $key => $value)                                                  
{                                                                                   
  $array2[$value['profile_field_id']]['value'][$value['value']] = $value['value'];                                                                                                                                                                                                                                             
}

使用您的数据集,它会为我输出:

Array
(   
    [214] => Array
        (   
            [value] => Array
                (   
                    [1] => 1
                    [2] => 2
                    [4] => 4
                    [8] => 8
                )

        )

    [215] => Array
        (   
            [value] => Array
                (   
                    [1] => 1
                    [2] => 2
                )

        )

)

要更改相同键/值对的输出,请从作业左侧删除第一个$ value ['value']。