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

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

WBOY
Release: 2016-06-06 19:49:36
Original
1300 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

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

$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

)

(PHP 5 >=5.5.0)

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

Related labels:
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