Home > php教程 > php手册 > body text

PHP中如何将二维数组转为一维数组

PHPz
Release: 2018-10-20 17:14:08
Original
1166 people have browsed it

在开发过程中,我们经常需要将二维数组转为一维数组,个人总结了2种方法,分享给大家

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

代码如下:

$msg = array(
  array(
    'id'=>'45',
    'name'=>'jack'
  ),
  array(
    'id'=>'34',
    'name'=>'mary'
  ),
  array(
    'id'=>'78',
    'name'=>'lili'
  ),
);
Copy after login

第一种方法:

代码如下:

foreach($msg as $k => $v){
    $ids[] = $id;
    $names[] = $name;
  }
Copy after login

第二种方法:

代码如下:

$ids = array_column($msg, 'id');
 $names = array_column($msg, 'name');
Copy after login

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

代码如下:

Array(
  [0]=>jack
  [1]=>mary
  [2]=>lili
)
Copy after login

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

print_r($n);的结果为:

代码如下:

Array(
  [45]=>jack
  [34]=>mary
  [78]=>lili
)
Copy after login

 

【相关教程推荐】

1. php编程从入门到精通全套视频教程
2. php从入门到精通 
3. bootstrap教程

source:php.cn
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template