转换PHP"分组"阵列"分段"排列 [英] Convert PHP "grouped" array to "segmented" array
问题描述
尝试将分组多维数组转换为分段多维数组。不知道如何解释呢准确,所以希望这些的print_r
业绩好解释。
Trying to convert a "grouped" multidimensional array to a "segmented" multidimensional array. Not sure how to explain it exactly so hopefully these print_r
results explain it better.
当前阵列
Array
(
[qty] => Array
(
[0] => 1
[1] => 1
[2] => 1
)
[item_id] => Array
(
[0] => RR332
[1] => FF586
[2] => QW865
)
[item_name] => Array
(
[0] => Widget 1
[1] => Widget 2
[2] => Widget 3
)
[price] => Array
(
[0] => 1.00
[1] => 1.50
[2] => 1.50
)
)
通缉阵列
Array
(
[0] => Array
(
[qty] => 1
[item_id] => RR332
[item_name] => Widget 1
[price] => 1.00
)
[1] => Array
(
[qty] => 1
[item_id] => FF586
[item_name] => Widget 2
[price] => 1.50
)
[2] => Array
(
[qty] => 1
[item_id] => QW865
[item_name] => Widget 3
[price] => 1.50
)
)
这似乎是它应该是一个简单的任务,但我一直没能还没有破解它。
This seems like it should be a simple task but I haven't been able to crack it yet.
我想preferably喜欢通过的当前阵列的创造的通缉阵列循环的如果可能的话。
I would preferably like to loop through the Current Array to create the Wanted Array if possible.
任何帮助是极大AP preciated!
Any help is greatly appreciated!
感谢。
推荐答案
我认为这将做的工作适合你,虽然我不具备良好的数据集,以测试对。
I think this will do the job for you, though I don't have a good data set to test against.
$wanted_array = array();
// Iterate over the outer array to get the text keys & inner arrays
foreach ($current_array as $txtkey=>$arr) {
// Iterate over each inner array to get the numeric key
foreach ($arr as $numkey=>$val) {
// Set a numeric key pointing to a new array
// onto the new outer array if it isn't already there
if (!isset($wanted_array[$numkey])) $wanted_array[$numkey] = array();
// Swap the keys of the outer and inner arrays.
$wanted_array[$numkey][$txtkey] = $val;
}
}
更新:从@ hakre的回答使用测试序列,在这里它是在实践中:
$current_array = array(
'qty' => array(
0 => 1,
1 => 1,
2 => 1
),
'item_id' => array(
0 => 'RR332',
1 => 'FF586',
2 => 'QW865'
),
'item_name' => array(
0 => 'Widget 1',
1 => 'Widget 2',
2 => 'Widget 3'
),
'price' => array(
0 => '1.00',
1 => '1.50',
2 => '1.50'
)
);
// Output:
Array
(
[0] => Array
(
[qty] => 1
[item_id] => RR332
[item_name] => Widget 1
[price] => 1.00
)
[1] => Array
(
[qty] => 1
[item_id] => FF586
[item_name] => Widget 2
[price] => 1.50
)
[2] => Array
(
[qty] => 1
[item_id] => QW865
[item_name] => Widget 3
[price] => 1.50
)
)
这篇关于转换PHP"分组"阵列"分段"排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!