PHP 中的多维数组

问题描述 投票:0回答:3

我在 PHP 中使用多维数组时遇到问题。

我认为这应该很简单,但是,我很难理解多维度。

我的数组看起来像这样:

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

    )

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

    )

)

我想以某种方式改变这个数组,使其看起来像这样,我看到的只是一个project_id的数组:

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

抱歉问了这么基本的问题。任何提示或线索都会很棒!

php arrays multidimensional-array
3个回答
4
投票
$arr = ...
$new_arr = array();
foreach ( $arr as $el ) {
    $new_arr[] = $el['projects_users']['project_id'];
}

或者,PHP 版本 >= 5.3:

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

第三种有趣的方式,与

reset

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

###性能

出于好奇/无聊,我对有或没有

reset
的迭代/功能风格进行了基准测试。我很惊讶地发现测试 4 在每次运行中都是获胜者 — 我认为
array_map
的开销比
foreach
多一点,但是(至少在这种情况下)这些测试表明情况并非如此!测试代码在这里。
http://pastie.org/2183604

$ 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

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

print_r($new);

0
投票

如果索引匹配很重要,您将需要执行类似的操作。

foreach ($orig_array as $key => $value) {
   $orig_array[$key] = $value['projects_users']['project_id'];
}
© www.soinside.com 2019 - 2024. All rights reserved.