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

WBOY
Release: 2016-06-20 13:05:21
Original
1476 people have browsed it

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

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

$msg = array(

  array(

    'id'=>'45s',

    'name'=>'jacks'

  ),

  array(

    'id'=>'3s4',

    'name'=>'masry'

  ),

  array(

    'id'=>'7s8',

    'name'=>'lili'

  ),

);
Copy after login

一般实现方法:

1解:

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

2解:

$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()这个函数在php5.5版本才出现;可以有第三个参数,如 $n = array_column($msg, 'name', 'id');

print_r($n);的结果为:

Array(
  [45]=>jacks
  [34]=>masry
  [78]=>lili
)
Copy after login

 


Related labels:
php
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!