如何通过数组键重新排列数组?

我只是想重新排列我的数组以进行正确的循环。我感到尊重谁可以帮助我解决这个问题。


My input array is:-


array(

'text'=>array('icon_title_1'=>'Test 1','icon_title_2'=>'Test 2'),

'image'=>array('icon_file_1',='test.jpg','icon_file_2'=>'test2.jpg')

 )


 My Required output array is:-


 array(

     0=>array(

         'text'=>'Test 1'

         'image'=>'test.jpg'    

     ),

     1=>array(

         'text'=>'Test 2'

         'image'=>'test2.jpg'   

     )

  );


慕桂英3389331
浏览 98回答 3
3回答

繁华开满天机

假设这是您输入的最终格式。您可以使用array_map解决方案$data = array(    'text'=>array('icon_title_1' =>'Test 1','icon_title_2'=>'Test 2'),    'image'=>array('icon_file_1' => 'test.jpg','icon_file_2'=>'test2.jpg'));$func = function($text, $image){    return  [            'text' => $text,            'image' => $image        ];};var_dump(array_map($func, $data['text'], $data['image']));输出array(2) {  [0]=>  array(2) {    ["text"]=>    string(6) "Test 1"    ["image"]=>    string(8) "test.jpg"  }  [1]=>  array(2) {    ["text"]=>    string(6) "Test 2"    ["image"]=>    string(9) "test2.jpg"  }}

UYOU

对于您给定的输入格式,您可以使用下面的代码来获得结果,假设内部数组键格式如 icon_title_1、icon_title_2、icon_title_3 等。和 icon_file_1、icon_file_2 等。$input = array('text'=>array(                'icon_title_1'=>'Test 1',                'icon_title_2'=>'Test 2'),'image'=>array(                'icon_file_1'=>'test.jpg',                'icon_file_2'=>'test2.jpg'));$output = array();$index = 0;foreach($input  as $key => $value){ foreach($value as $k => $v){     $indexPart = explode("_",$k);     $index = $indexPart[count($indexPart)-1];     $output[$index][$key] = $v; }}print_r($output);

精慕HU

您可以使用简单的嵌套foreach循环转换数组:$result = array();foreach ($array as $key => $arr) {    $i = 0;    foreach ($arr as $v) {        $result[$i++][$key] = $v;    }}print_r($result);输出:Array(    [0] => Array        (            [text] => Test 1            [image] => test.jpg        )    [1] => Array        (            [text] => Test 2            [image] => test2.jpg    ))
打开App,查看更多内容
随时随地看视频慕课网APP