有没有办法将多个数组与相同数量的项目组合在一起?请参阅下面的4个阵列,里面有5个项目:
$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');
预期结果:
[0] => Array
(
[0] => Type 1
[1] => Description 1
[2] => Brand 1
[3] => Model 1
)
[1] => Array
(
[0] => Type 2
[1] => Description 2
[2] => Brand 2
[3] => Model 2
)
[2] => Array
(
[0] => Type 3
[1] => Description 3
[2] => Brand 3
[3] => Model 3
)
[3] => Array
(
[0] => Type 4
[1] => Description 4
[2] => Brand 4
[3] => Model 4
)
[4] => Array
(
[0] => Type 5
[1] => Description 5
[2] => Brand 5
[3] => Model 5
)
我不是PHP专家,请帮帮我:)。
谢谢。
答案 0 :(得分:0)
试试这段代码:
$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');
$result = array();
foreach($type as $key=>$val){ // Loop though one array
$val2 = $desc[$key];
$val3 = $brand[$key];
$val4 = $model[$key];
$result[$key] =array($val,$val2, $val3,$val4);
}
print_r($result);
答案 1 :(得分:0)
通过任何数组进行简单循环,使用该数组的键获取其数组数据并创建新数组
$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');
foreach($type as $key=>$type_val){ // Loop though one array
$desc_val = $desc[$key] ?? "";
$brand_val = $brand[$key] ?? "";
$model_val = $model[$key] ?? "";
$result[$key] = array($type_val,$desc_val,$brand_val,$model_val); // combine
}
print_r($result);
注意: ??
仅适用于PHP 7 +旧版本更改$desc[$key] ?? ""
至isset($desc[$key]) ? $desc[$key] : ""
答案 2 :(得分:0)
这是完美且经过测试的代码:
<?php
$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');
$result = array();
foreach ($type as $id => $key) {
$result[$id] = array($key,$desc[$id],$brand[$id],$model[$id]);
}
echo "<pre>";print_r($result);
?>
答案 3 :(得分:0)
array_map就是你真正需要的。
$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');
$res = array_map(function(...$val) {return $val;}, $type, $desc, $brand, $model);
print_r($res);