使用键切换嵌套数组值,并相应地反转计数

时间:2014-05-08 00:15:24

标签: php arrays

我拍了几张照片,并且我已经标记了人物。我有一个数组,其键是photo_id,其值是照片中标记的person_id数组:

Array
(
    [19] => Array
        (
            [0] => 12
        )

    [21] => Array
        (
            [0] => 177
        )

    [26] => Array
        (
            [0] => 27
            [1] => 4
        )

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

    [28] => Array
        (
            [0] => 934
            [1] => 935
            [2] => 234
        )
)

我想要的是一个以person_id为键的数组,以及将它们标记为值的照片。例如, 27 的人在照片 26 27 。我将如何创建这个新阵列?非常感谢你!

2 个答案:

答案 0 :(得分:0)

您只需使用person_id作为新密钥和nphoto_id条目的条目来循环遍历数组并创建新数组:

$new_array = array();

foreach($original_array as $photo_id => $values) {
    foreach($values as $person_id) {
        // initialize array key if it doesn't already exist
        if(!array_key_exists($person_id, $new_array)) {
            $new_array[$person_id] = array();
        }
        // add photo id to the array
        $new_array[$person_id][] = $photo_id;
    }
}

这是一个演示:https://eval.in/147879

答案 1 :(得分:0)

您可以使用array_walk()in_array()的组合来获得所需的内容:

$pictures = Array( 19 => [12], 21 => [177], 26 => [27,4], 27 => [27,4], 28 => [934,935,234] );
$included = [];
$person = 27;

//The following line is all you need
array_walk( $pictures, function(&$picture, $pictureId, $params) { 
        if( in_array( $params[1], $picture, TRUE ) )
            array_push( $params[0], $pictureId );
    }, [&$included, $person] ); 

print_r( $included );

将打印出来:

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

如果要完全反转数组,则可以使用双foreach循环来迭代它们:

$pictures = [19 => [12], 21 => [177], 26 => [27,4], 27 => [27,4], 28 => [934,935,234] ];
$included = [];
foreach( $pictures as $pictureId => $picture ) {
    foreach( $picture as $personId ) {
        if( !isset( $included[$personId] ) )
            $included[$personId] = [];
        array_push( $included[$personId], $pictureId );
    }
}; 
print_r( $included );

结果将打印出来:

Array
(
    [12] => Array
        (
            [0] => 19
        )

    [177] => Array
        (
            [0] => 21
        )

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

    [4] => Array
        (
            [0] => 26
            [1] => 27
        )

    [934] => Array
        (
            [0] => 28
        )

    [935] => Array
        (
            [0] => 28
        )

    [234] => Array
        (
            [0] => 28
        )

)