PHP函数array_column

array_column返回输入数组中单个列的值

接受$array, $column, $index_key三个参数

  • $column指定返回列值的列名称
  • $column为null,返回$index_key的值作为索引的完整数组
  • $index_key如果指定,$index_key的值将作为$column值的索引
/**
 * (PHP 5 &gt;=5.5.0)<br/>
 * Return the values from a single column in the input array
 * @link https://secure.php.net/manual/en/function.array-column.php
 * @param array $array <p>A multi-dimensional array (record set) from which to pull a column of values.</p>
 * @param mixed $column <p>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. It may also be NULL to return complete arrays (useful together with index_key to reindex the array).</p>
 * @param mixed $index_key [optional] <p>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.</p>
 * @return array Returns an array of values representing a single column from the input array.
 * @since 5.5
 */
function array_column(array $array, $column, $index_key = null) { }

示例一:指定第二个参数

$arr = [
    ['nid' => 300311,'name' => 'Lily', 'age' => 18],
    ['nid' => 300312,'name' => 'Tom', 'age' => 19],
    ['nid' => 300313,'name' => 'Rose', 'age' => 16],
];

var_dump(array_column($arr, 'name'));
//结果
//array(3) {
//    [0] =>
//  string(4) "Lily"
//    [1] =>
//  string(3) "Tom"
//    [2] =>
//  string(4) "Rose"
//}

示例二:指定第三个参数

$arr = [
    ['nid' => 300311,'name' => 'Lily', 'age' => 18],
    ['nid' => 300312,'name' => 'Tom', 'age' => 19],
    ['nid' => 300313,'name' => 'Rose', 'age' => 16],
];

var_dump(array_column($arr, 'name', 'nid'));
//结果
//array(3) {
//    [300311] =>
//  string(4) "Lily"
//    [300312] =>
//  string(3) "Tom"
//    [300313] =>
//  string(4) "Rose"
//}

 示例三:第二个参数为null时

$arr = [
    ['nid' => 300311,'name' => 'Lily', 'age' => 18],
    ['nid' => 300312,'name' => 'Tom', 'age' => 19],
    ['nid' => 300313,'name' => 'Rose', 'age' => 16],
];

var_dump(array_column($arr, null, 'nid'));
//结果
//array(3) {
//    [300311] =>
//  array(3) {
//        'nid' =>
//    int(300311)
//    'name' =>
//    string(4) "Lily"
//    'age' =>
//    int(18)
//  }
//  [300312] =>
//  array(3) {
//        'nid' =>
//    int(300312)
//    'name' =>
//    string(3) "Tom"
//    'age' =>
//    int(19)
//  }
//  [300313] =>
//  array(3) {
//        'nid' =>
//    int(300313)
//    'name' =>
//    string(4) "Rose"
//    'age' =>
//    int(16)
//  }
//}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值