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

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

WBOY
WBOYOriginal
2016-06-01 11:52:231261browse

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

复制代码 代码如下:
$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:
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