开发者

Multidimensional Arrays in PHP

I'm having trouble with multidimensional arrays in PHP.

I'm assuming t开发者_运维问答his should be simple but, I'm having difficulty wrapping my mind around the multi-dimensions.

The array that I have looks like this:

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

    )

[1] => Array
    (
        [projects_users] => Array
            (
                [project_id] => 2
            )

    )

)

I would like to somehow alter this array to look like this, where all I see is an array of the project_id:

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

Sorry for such an elementary question. Any hints or clues would be great!


$arr = ...
$new_arr = array();
foreach ( $arr as $el ) {
    $new_arr[] = $el['projects_users']['project_id'];
}

Or, with PHP version >= 5.3:

$new_arr = array_map(function ($e) { return $e['projects_users']['project_id']; }, $arr);

A third fun way, with reset:

$arr = ...
$new_arr = array();
foreach ( $arr as $el ) {
    $new_arr[] = reset(reset($el));
}

Performance

Out of curiosity / boredom I benchmarked the iterative / functional styles with and without reset. I was surprised to see that test 4 was the winner in every run — I thought that array_map had a bit more overhead than foreach, but (at least in this case) these tests show otherwise! Test code is here.

$ php -v
PHP 5.3.4 (cli) (built: Dec 15 2010 12:15:07) 
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
$ php test.php
Test 1, Iterative - 34.093856811523 microseconds
Test 2, array_map - 37.908554077148 microseconds
Test 3, Iterative with reset - 107.0499420166 microseconds
Test 4, array_map with reset - 25.033950805664 microseconds
$ php test.php
Test 1, Iterative - 32.186508178711 microseconds
Test 2, array_map - 39.100646972656 microseconds
Test 3, Iterative with reset - 35.04753112793 microseconds
Test 4, array_map with reset - 24.080276489258 microseconds
$ php test.php
Test 1, Iterative - 31.948089599609 microseconds
Test 2, array_map - 36.954879760742 microseconds
Test 3, Iterative with reset - 32.901763916016 microseconds
Test 4, array_map with reset - 24.795532226562 microseconds
$ php test.php
Test 1, Iterative - 29.087066650391 microseconds
Test 2, array_map - 34.093856811523 microseconds
Test 3, Iterative with reset - 33.140182495117 microseconds
Test 4, array_map with reset - 25.98762512207 microseconds


foreach($arrays as $array){
    $new[] = $array['projects_user']['project_id'];
}

print_r($new);


if it is important that indexes match, you will want to do something like this.

foreach ($orig_array as $key => $value) {
   $orig_array[$key] = $value['projects_users']['project_id'];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜