获取多维数组中特定列的所有值 [英] Get all values of a specific column in a multidimensional array

查看:88
本文介绍了获取多维数组中特定列的所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组,比如说x列数和y行数.

I have a multidimensional array, that has say, x number of columns and y number of rows.

我想要第三列中的所有值.

I want specifically all the values in the 3rd column.

执行此操作的明显方法是将其放入这样的for循环中

The obvious way to go about doing this is to put this in a for loop like this

for(i=0;i<y-1;i++)
{
   $ThirdColumn[] = $array[$i][3];
}

,但是这里涉及O(n)明显的时间复杂性.是否有一种内置的方法可以简单地从数组中提取这些行中的每一行而无需循环.

but there is an obvious time complexity of O(n) involved here. Is there a built in way for me to simply extract each of these rows from the array without having to loop in.

例如(这在偏离路线上不起作用)

For example (this does not work offcourse)

$ThirdColumn  = $array[][3]

推荐答案

给出一个二维数组$channels:

$channels = array(
    array(
        'id' => 100,
        'name' => 'Direct'
    ),
    array(
        'id' => 200,
        'name' => 'Dynamic'
    )
);

一种不错的方法是使用 array_map :

A nice way is using array_map:

$_currentChannels = array_map(function ($value) {
    return  $value['name'];
}, $channels);

,如果您是通过 array_column 的有力(php 5.5 +):

and if you are a potentate (php 5.5+) through array_column:

$_currentChannels = array_column($channels, 'name');

两者均导致:

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


星级嘉宾: array_map (php4 +)和


Star guests: array_map (php4+) and array_column (php5.5+)

// array array_map ( callable $callback , array $array1 [, array $... ] )
// array array_column ( array $array , mixed $column_key [, mixed $index_key = null ] )

这篇关于获取多维数组中特定列的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆