php中将二维数组转为一维数组的方法是:可以使用array_column()函数来实现。该函数返回一个数组,数组的值为输入数组中某个单一列的值。具体方法如:【array_column($records, 'first_name')】。
相关函数介绍:
(推荐教程:php教程)
array_column() 函数返回一个数组,数组的值为输入数组中某个单一列的值。
函数语法:
array_column(array,column_key,index_key);
参数说明:
立即学习“PHP免费学习笔记(深入)”;
array 必需。指定要使用的多维数组(记录集)。
column_key 必需。需要返回值的列。可以是索引数组的列的整数索引,或者是关联数组的列的字符串键值。该参数也可以是 NULL,此时将返回整个数组(配合index_key 参数来重置数组键的时候,非常管用)。
index_key 可选。作为返回数组的索引/键的列。
现有如下数组:
$records = [ [ 'id' => 2135, 'first_name' => 'John', 'last_name' => 'Doe', ], [ 'id' => 3245, 'first_name' => 'Sally', 'last_name' => 'Smith', ], [ 'id' => 5342, 'first_name' => 'Jane', 'last_name' => 'Jones', ], [ 'id' => 5623, 'first_name' => 'Peter', 'last_name' => 'Doe', ] ];
代码实现:
示例1:
<?php $first_names = array_column($records, 'first_name'); var_dump($first_names); ?>
打印结果:
$first_names = ['John','Sally','Jane','Peter'];
示例2:
<?php $first_names = array_column($records, 'first_name','id'); var_dump($first_names); ?>
打印结果:
$first_names = [2135 =>'John',3245 => 'Sally',5342 => 'Jane',5623 => 'Peter'];
以上就是php中怎么将二维数组转为一维数组的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号