为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕桂英3389331 2022-05-27 16:05:29
我只是想重新排列我的数组以进行正确的循环。我感到尊重谁可以帮助我解决这个问题。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'        )  );
查看完整描述

3 回答

?
繁华开满天机

TA贡献1816条经验 获得超4个赞

假设这是您输入的最终格式。您可以使用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"

  }

}


查看完整回答
反对 回复 2022-05-27
?
UYOU

TA贡献1878条经验 获得超4个赞

对于您给定的输入格式,您可以使用下面的代码来获得结果,假设内部数组键格式如 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);


查看完整回答
反对 回复 2022-05-27
?
精慕HU

TA贡献1845条经验 获得超8个赞

您可以使用简单的嵌套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

    )

)


查看完整回答
反对 回复 2022-05-27
  • 3 回答
  • 0 关注
  • 83 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信