Home  >  Article  >  Backend Development  >  php二维数组转一维数组方法

php二维数组转一维数组方法

WBOY
WBOYOriginal
2016-06-20 13:05:211515browse

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

php二维数组转一维数组,下面介绍两种方法

$msg = array(

  array(

    'id'=>'45s',

    'name'=>'jacks'

  ),

  array(

    'id'=>'3s4',

    'name'=>'masry'

  ),

  array(

    'id'=>'7s8',

    'name'=>'lili'

  ),

);

一般实现方法:

1解:

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

2解:

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

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

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

快速实现方法:

注意:array_column()这个函数在php5.5版本才出现;可以有第三个参数,如 $n = array_column($msg, 'name', 'id');

print_r($n);的结果为:

Array(
  [45]=>jacks
  [34]=>masry
  [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