Two ways to convert a two dimensional array into a one dimensional array

  • 2021-06-28 11:50:50
  • OfStack

How to convert the following 2-dimensional array to 1-dimensional array.


$msg = array(
 * array(
 * 'id'=>'45',
 * 'name'=>'jack'
 * ),
 * array(
 * 'id'=>'34',
 * 'name'=>'mary'
 * ),
 * array(
 * 'id'=>'78',
 * 'name'=>'lili'
 * ),
);

Method 1:


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

Method 2:


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

Both of the above solutions print_r ($names);The results are as follows:


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

Note: array_column();There can be a third parameter, such as $n = array_column ($msg,'name','id');

print_r ($n);The results are:


Array(
 * [45]=>jack
 * [34]=>mary
 * [78]=>lili
)


Related articles: