How to convert the following two-dimensional array into a one-dimensional array.
$msg = array(
array(
'id'=>'45',
'name'=>'jack'
),
array(
'id'=>'34',
'name'=>'mary'
),
array(
'id'=>'78',
'name'=>'lili'
),
);
1 Solution: foreach($msg as $k => $v){
$ids[] = $id;
$names[] = $name;
}
2 solution: $ids = array_column($msg, 'id');
$names = array_column($msg, 'name');
The result of the above two solutions print_r($names); is:
Array(
[0]=>jack
[1]=>mary
[2]=>lili
)
Note: array_column(); can have a third parameter, such as $n = array_column($msg, 'name', 'id');
The result ofprint_r($n); is:
Array(
[45]=>jack
[34]=>mary
[78]=>lili
)
Reference: array array_column ( array $array
, mixed $column_key
[, mixed $index_key
= null ] )