百科狗-知识改变命运!
--

array_column() - 返回数组中指定的一列 - php 数组函数

梵高1年前 (2023-11-21)阅读数 22#技术干货
文章标签数组

array_column()

(PHP 5 >= 5.5.0, PHP 7)

返回数组中指定的一列

说明

array_column(array $input,mixed $column_key[,mixed $index_key= null]): array

array_column()返回$input数组中键值为$column_key的列,如果指定了可选参数$index_key,那么$input数组中的这一列的值将作为返回数组中对应值的键。

参数

$input

需要取出数组列的多维数组。如果提供的是包含一组对象的数组,只有 public 属性会被直接取出。为了也能取出 private 和 protected 属性,类必须实现__get()__isset()魔术方法。

$column_key

需要返回值的列,它可以是索引数组的列索引,或者是关联数组的列的键,也可以是属性名。也可以是NULL,此时将返回整个数组(配合$index_key参数来重置数组键的时候,非常管用)

$index_key

array_column() - 返回数组中指定的一列 - php 数组函数

作为返回数组的索引/键的列,它可以是该列的整数索引,或者字符串键值。

返回值

从多维数组中返回单列数组。

更新日志

版本说明
7.0.0$input参数现在可以是包含对象的数组。

范例

从结果集中取出first names列

以上例程会输出:

Array
(
    [0] => John
    [1] => Sally
    [2] => Jane
    [3] => Peter
)

从结果集中总取出last names列,用相应的id作为键值

以上例程会输出:

Array
(
    [2135] => Doe
    [3245] => Smith
    [5342] => Jones
    [5623] => Doe
)

username 列是从对象获取 public 的"username"属性

以上例程会输出:

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

获取 username 列,从对象通过魔术方法__get()获取 private 的"username"属性。

以上例程会输出:

Array
(
    [0] => Fred
    [1] => Jane
    [2] => John
)
如果不提供__isset(),会返回空数组。

参见

  • » Recommended userland implementation for PHP lower than 5.5
if array_column does not exist the below solution will work.
if(!function_exists("array_column"))
{
  function array_column($array,$column_name)
  {
    return array_map(function($element) use($column_name){return $element[$column_name];}, $array);
  }
}
Because the function was not available in my version of PHP, I wrote my own version and extended it a little based on my needs.
When you give an $indexkey value of -1 it preserves the associated array key values.
EXAMPLE:
$sample = array(
  'test1' => array(
    'val1' = 10,
    'val2' = 100
  ),
  'test2' => array(
    'val1' = 20,
    'val2' = 200
  ),
  'test3' => array(
    'val1' = 30,
    'val2' = 300
  )
);
print_r(array_column_ext($sample,'val1'));
OUTPUT:
Array
(
  [0] => 10
  [1] => 20
  [2] => 30
)
print_r(array_column_ext($sample,'val1',-1));
OUTPUT:
Array
(
  ['test1'] => 10
  ['test2'] => 20
  ['test3'] => 30
)
print_r(array_column_ext($sample,'val1','val2'));
OUTPUT:
Array
(
  [100] => 10
  [200] => 20
  [300] => 30
) 
You can also use array_map fucntion if you haven't array_column().
example:
$a = array(
  array(
    'id' => 2135,
    'first_name' => 'John',
    'last_name' => 'Doe',
  ),
  array(
    'id' => 3245,
    'first_name' => 'Sally',
    'last_name' => 'Smith',
  )
);
array_column($a, 'last_name');
becomes
array_map(function($element){return $element['last_name'];}, $a);
This function does not preserve the original keys of the array (when not providing an index_key).
You can work around that like so: 
Some remarks not included in the official documentation.
1) array_column does not support 1D arrays, in which case an empty array is returned.
2) The $column_key is zero-based.
3) If $column_key extends the valid index range an empty array is returned.
array_column implementation that works on multidimensional arrays (not just 2-dimensional): 
array_column() will return duplicate values. 
Instead of having to use array_unique(), use the $index_key as a hack.
**Caution: This may get messy when setting the $column_key and/or $index_key as integers.** 
If you need to extract more than one column from an array, you can use array_intersect_key on each element, like so:
function array_column_multi(array $input, array $column_keys) {
  $result = array();
  $column_keys = array_flip($column_keys);
  foreach($input as $key => $el) {
    $result[$key] = array_intersect_key($el, $column_keys);
  }
  return $result;
}
I added a little more functionality to the more popular answers here to support the $index_key parameter for PHP 
Here's a neat little snippet for filtering a set of records based on a the value of a column: 
//php 
if (!function_exists('array_column'))
{
  function array_column($input, $column_key=null, $index_key=null)
  {
    $result = array();
    $i = 0;
    foreach ($input as $v)
    {
      $k = $index_key === null || !isset($v[$index_key]) ? $i++ : $v[$index_key];
      $result[$k] = $column_key === null ? $v : (isset($v[$column_key]) ? $v[$column_key] : null);
    }
    return $result;
  }
}
Note that this function will return the last entry when possible keys are duplicated. 
Please note this function accepts 2D-arrays ONLY, and silently returns empty array when non-array argument is provided.
Code:
class testObject {
  public $a = 123;
}
$testArray = [new testObject(), new testObject(), new testObject()];
$result = array_column($testArray, 'a')); //array(0) { }
a simple solution:
function arrayColumn(array $array, $column_key, $index_key=null){
    if(function_exists('array_column ')){
      return array_column($array, $column_key, $index_key);
    }
    $result = [];
    foreach($array as $arr){
      if(!is_array($arr)) continue;
      if(is_null($column_key)){
        $value = $arr;
      }else{
        $value = $arr[$column_key];
      }
      if(!is_null($index_key)){
        $key = $arr[$index_key];
        $result[$key] = $value;
      }else{
        $result[] = $value;
      }
    }
    return $result;
  }
If array_column is not available you can use the following function, which also has the $index_key parameter:
if (!function_exists('array_column')) {
  function array_column($array, $column_key, $index_key = null) 
  {
    return array_reduce($array, function ($result, $item) use ($column_key, $index_key) 
    {
      if (null === $index_key) {
        $result[] = $item[$column_key];
      } else {
        $result[$item[$index_key]] = $item[$column_key];
      }
      return $result;
    }, []);
  }
}
Another option for older PHP versions (pre 5.5.0) is to use array_walk(): 
This didn't work for me recursively and needed to come up with a solution. 
Here's my solution to the function:
if ( ! function_exists( 'array_column_recursive' ) ) {
  /**
   * Returns the values recursively from columns of the input array, identified by
   * the $columnKey.
   *
   * Optionally, you may provide an $indexKey to index the values in the returned
   * array by the values from the $indexKey column in the input array.
   *
   * @param array $input   A multi-dimensional array (record set) from which to pull
   *             a column of values.
   * @param mixed $columnKey The column of values to return. This value may be the
   *             integer key of the column you wish to retrieve, or it
   *             may be the string key name for an associative array.
   * @param mixed $indexKey (Optional.) The column to use as the index/keys for
   *             the returned array. This value may be the integer key
   *             of the column, or it may be the string key name.
   *
   * @return array
   */
  function array_column_recursive( $input = NULL, $columnKey = NULL, $indexKey = NULL ) {
    // Using func_get_args() in order to check for proper number of
    // parameters and trigger errors exactly as the built-in array_column()
    // does in PHP 5.5.
    $argc  = func_num_args();
    $params = func_get_args();
    if ( $argc 
Retrieve multiple columns from an array:
$columns_wanted = array('foo','bar');
$array = array('foo'=>1,'bar'=>2,'foobar'=>3);
$filtered_array = array_intersect_key(array_fill_keys($columns_wanted,''));
//filtered_array 
// array('foo'=>1,'bar'=>2);
Value for existing key in the resulting array is rewritten with new value if it exists in another source sub-array.
Presented function is good when You want to flatten nested array base on only one column, but if You want to flatten whole array You can use this method:
/**
   * Method that transforms nested array into the flat one in below showed way:
   * [
   *   [
   *     [0]=>'today',
   *   ],
   *   [
   *     [0]=>'is',
   *     [1]=>'very',
   *     [2]=>  [
   *           [0]=>'warm'
   *         ],
   *   ],
   * ]
   *
   * Into:
   *
   * ['today','is','very','warm']
   *
   * @param $input
   * @return array
   */
  private function transformNestedArrayToFlatArray($input)
  {
    $output_array = [];
    if (is_array($input)) {
      foreach ($input as $value) {
        if (is_array($value)) {
          $output_array = array_merge($output_array, $this->transformNestedArrayToFlatArray($value));
        } else {
          array_push($output_array, $value);
        }
      }
    } else {
      array_push($output_array, $input);
    }
    return $output_array;
  }
 

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)