我有一个像这样的二维数组:
Array
(
[id] => Array
(
[0] => 1
)
[name] => Array
(
[0] => john
)
[dept] => Array
(
[0] => val_1
[1] => val_2
)
[to] => Array
(
[0] => one
[1] => two
)
)
无论如何,我可以将此数组转换为多个单个数组,如下所示:
Array
(
[id] => 1
[name] => john
[dept] => val_1
[to] => one
)
Array
(
[id] => 1
[name] => john
[dept] => val_1
[to] => two
)
Array
(
[id] => 1
[name] => john
[dept] => val_2
[to] => one
)
Array
(
[id] => 1
[name] => john
[dept] => val_2
[to] => two
)
我使用了array_merge但未能得到我想要的东西。任何帮助表示赞赏
答案 0 :(得分:0)
试试这个(解决方案可能不是最干净的!):
<?php
$arr = [
'id' => [
1
],
'name' => [
'john'
],
'dept' => [
'val_1', 'val_2'
],
'to' => [
'one', 'two'
]
];
function convert($arr, $outArrCount) {
$total = [];
for ($i=0; $i<$outArrCount; $i++) {
$entry = [];
array_walk($arr, function ($val, $key) use (&$entry, $i, $outArrCount) {
if (count($val) > 1) {
$entry[$key] = $val[ floor((count($val) / $outArrCount) * $i) ];
}
else {
$entry[$key] = $val;
}
});
$total[] = $entry;
};
return $total;
}
var_dump(convert($arr, 4));
答案 1 :(得分:0)
使用此功能将帮助您重组阵列。
function loopArrayMerger(array $array) {
if (! $array) {
return array ();
}
return call_user_func_array ( 'array_merge', $array );
}
答案 2 :(得分:0)
我发现以下功能有助于回答我的问题:
function array_cartesian() {
$_ = func_get_args();
if(count($_) == 0)
return array(array());
$a = array_shift($_);
$c = call_user_func_array(__FUNCTION__, $_);
$r = array();
foreach($a as $v)
foreach($c as $p)
$r[] = array_merge(array($v), $p);
return $r;
}
我可以按如下方式使用它:
$cross = array_cartesian(
$arr[id],
$arr[name],
$arr[dept],
$arr[to]);
print_r($cross);