这是我从我的表单中获得的数组形式多个复选框.
$test1 = array(
'0' => 'test1',
'1' => 'test2',
'2' => 'test3'
);
$test2 = array(
'0' => 'test21',
'1' => 'test22',
'2' => 'test23'
);
$test3 = array(
'0' => 'test31',
'1' => 'test32',
'2' => 'test33'
);
$test4 = array(
'0' => 'test41',
'1' => 'test42',
'2' => 'test43'
);
Run Code Online (Sandbox Code Playgroud)
我需要将此数组转换为如下所示:
$result_needed = [
'0' => ['0' => 'test1', '1' => 'test21', '2' => 'test31', '3' => 'test41'],
'1' => ['0' => 'test2', '1' => 'test22', '2' => 'test32', '3' => 'test42'],
AND SO ON....
];
Run Code Online (Sandbox Code Playgroud)
我试图将每个数组添加到最终数组中,然后在其上使用foreach循环它得到结果,但它没有帮助.这是我试过的.
$final = ['test1' => $test1, 'test2' => $test2, 'test3' => $test3, 'test4' => $test4];
echo "<pre>";
$step1 = array();
foreach($final as $key => $val){
$step1[$key] = $val;
}
print_r($step1);
Run Code Online (Sandbox Code Playgroud)
您可以使用循环并推送到结果数组
$final = ['test1' => $test1, 'test2' => $test2, 'test3' => $test3, 'test4' => $test4];
$step1 = [];
foreach ($final as $tests) {
foreach ($tests as $key => $value) {
if (!array_key_exists($key, $step1)) {
$step1[$key] = [];
}
$step1[$key][] = $value;
}
}
print_r($step1);
Run Code Online (Sandbox Code Playgroud)