简体   繁体   中英

How do I flatten an associative array into another associative array?

I am having this array :

array(
    'name'=> 'abc',
    'age'=> 30,
    'sex'=> 'male'
)

and i want to make this array in this way :

array(
    0 => 'name',
    1 => 'abc',
    2 => 'age',
    3 => 30,
    4 => 'sex',
    5 => 'male'
)

here it is

$array1 = array(
'name'=> 'abc',
'age'=> 30,
'sex'=> 'male') ;
$array2 = [];
foreach ($array1 as $key => $value) {
array_push($array2,$key,$value); }

You could do something like this:

$mArr = [ 
          'name'=> 'abc',
          'age'=> 30,
          'sex'=> 'male'
        ];
$oArr = [];
foreach($mArr as $k => $v) {
        $oArr[] = $k;
        $oArr[] = $v;
}
var_dump($oArr);
/*
array(6) {
  [0]=>
  string(4) "name"
  [1]=>
  string(3) "abc"
  [2]=>
  string(3) "age"
  [3]=>
  int(30)
  [4]=>
  string(3) "sex"
  [5]=>
  string(4) "male"
}
*/

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM