从三级多维数组的列中的列中获取值

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

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

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

我的数组看起来像这样:

[
    ['projects_users' => ['project_id' => 1]],
    ['projects_users' => ['project_id' => 2]],
]

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

Array
(
  [0] => 1
  [1] => 2
)
php arrays multidimensional-array
4个回答
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'];
}

0
投票

此任务也可以通过在无体循环中使用数组解构语法来完成。请注意,子数组键已被访问以及目标深度值所在的位置,请写入

$result[]
将该值推入结果中。

这种方法的好处是不需要声明第三个/临时变量(仅声明输入和结果变量)。

代码:(演示

$result = [];
foreach ($array as ['projects_users' => ['project_id' => $result[]]]);
var_export($result);

如果只声明输入变量,您可以通过调用

array_column()
两次来达到所需的结果。

代码:(演示

var_export(
    array_column(
        array_column($array, 'projects_users'),
        'project_id'
    )
);
© www.soinside.com 2019 - 2024. All rights reserved.