PHP数组与现有结构的新结构形式

时间:2012-10-24 10:21:31

标签: php

我有一个SQL查询,它以下列格式给出了数组。基本上,第0个元素是event_id,第一个元素是与事件相关的photo_id。以下是数组

Array
(
[0] => Array
    (
        [0] => 1
        [1] => 1
    )

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

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

[3] => Array
    (
        [0] => 0
        [1] => 4
    )

[4] => Array
    (
        [0] => 0
        [1] => 5
    )

[5] => Array
    (
        [0] => 1
        [1] => 6
    )

[6] => Array
    (
        [0] => 0
        [1] => 7
    )

[7] => Array
    (
        [0] => 1
        [1] => 8
    )

[8] => Array
    (
        [0] => 0
        [1] => 9
    )

[9] => Array
    (
        [0] => 1
        [1] => 10
    )

[10] => Array
    (
        [0] => 2
        [1] => 11
    )

[11] => Array
    (
        [0] => 2
        [1] => 12
    )

)

我需要将所有第0个元素转换为键,将第一个元素转换为值wrt。即所有相同的事件id都有自己的一组照片。所以输出应该像:

array(
    [1]=>[1,2,3,6,8,10]
    [0]=>[4,5,7,9]
    [2]=>[11,12]

谢谢!

2 个答案:

答案 0 :(得分:2)

$newArray = array ();

foreach ($array as $key => $value)
{
    $newArray[$value[0]][] = $value[1];
}

print_r($newArray);

答案 1 :(得分:1)

你走了:

$res = array();
foreach($arr as $k=>$v){
    $res[$v[0]][]=$v[1];
}
print_r($res);