Home > php教程 > php手册 > 快速实现:将二维数组转为一维数组

快速实现:将二维数组转为一维数组

WBOY
Release: 2016-06-13 09:34:51
Original
1429 people have browsed it

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

$msg = array(

  array(

    'id'=>'45',

    'name'=>'jack'

  ),

  array(

    'id'=>'34',

    'name'=>'mary'

  ),

  array(

    'id'=>'78',

    '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();可以有第三个参数,如 $n = array_column($msg, 'name', 'id');

print_r($n);的结果为:

Array(

  [45]=>jack

  [34]=>mary

  [78]=>lili

)

参考:array array_column ( array $array , mixed $column_key [, mixed $index_key = null ] )

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