PHP Use array map to reOrder an array

无人久伴 提交于 2019-12-13 09:19:13

问题


I need to reOrder this array with one function.

From (My actual array):

array:2 [▼
  0 => array:2 [▼
    "way" => 0
    "period" => "MONTH"
  ]
  1 => array:2 [▼
    "way" => 1
    "period" => "3MONTHS"
  ]
]

To (I would like this array):

array:2 [▼
  0 => array:1 [▼
    "MONTH" => 0
  ]
  1 => array:1 [▼
    "3MONTHS" => 1
  ]
]

Can I do that with array_map() function?


回答1:


You can simply use foreach instead like as

foreach($your_arr as &$v){
    $v = [$v["period"] => $v["way"]];
}
print_r($your_arr);

Or using array_map

$your_arr = array_map(function($v){ return [$v["period"] => $v["way"]]; },$your_arr);
print_r($your_arr);



回答2:


Use array_column() as

$data = array_column($array, 'way','period');

That convert period as key and way as its value



来源:https://stackoverflow.com/questions/38263969/php-use-array-map-to-reorder-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!