Home > Backend Development > PHP Tutorial > 将二维数组转为一维数组的2种方法_PHP

将二维数组转为一维数组的2种方法_PHP

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-01 11:52:23
Original
1302 people have browsed it

如何将下面的二维数组转为一维数组。

复制代码 代码如下:
$msg = array(
  array(
    'id'=>'45',
    'name'=>'jack'
  ),
  array(
    'id'=>'34',
    'name'=>'mary'
  ),
  array(
    'id'=>'78',
    'name'=>'lili'
  ),
);

第一种方法:

复制代码 代码如下:
foreach($msg as $k => $v){
    $ids[] = $id;
    $names[] = $name;
  }

第二种方法:

复制代码 代码如下:
$ids = array_column($msg, 'id');
 $names = array_column($msg, 'name');

以上两种解法print_r($names);后的结果为:

复制代码 代码如下:
Array(
  [0]=>jack
  [1]=>mary
  [2]=>lili
)

注意:array_column();可以有第三个参数,如 $n = array_column($msg, 'name', 'id');

print_r($n);的结果为:

复制代码 代码如下:
Array(
  [45]=>jack
  [34]=>mary
  [78]=>lili
)

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template