Php 如何按数组键重新排列数组?
我只是想重新排列我的数组以获得正确的循环。 我很尊重能帮我解决这个问题的人Php 如何按数组键重新排列数组?,php,arrays,Php,Arrays,我只是想重新排列我的数组以获得正确的循环。 我很尊重能帮我解决这个问题的人 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:-
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'
)
);
假设这是输入的最终格式。您可以使用
array\u 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"
}
}
对于给定的输入格式,您可以使用以下代码获得结果,假设内部数组键格式为icon_title_1、icon_title_2、icon_title_3等。。以及图标文件1、图标文件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);
您可以使用简单的嵌套
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
)
)
使用也可以使用foreach循环:
$newarray = array();
foreach ($array as $k => $arr) {
$i = 0;
foreach ($arr as $ar) {
$newarray[$i++][$k] = $ar;
}
}
print_r($newarray);
您的输入数组是什么?您当前使用什么代码获取输出数组?请也发布您的输入数组。@nick我只是使用foreach循环获取所需数组。我的输入数组与输出数组相同。但您的输入数据是什么?@PawanDongol无需担心。我希望它对你有用。