我有以下数组包含2个元素:
$attribute_metric = array(2)
{
[0]=>
array(2) {
[0]=>
string(5) "white"
[1]=>
string(6) " Black"
}
[1]=>
array(3) {
[0]=>
string(1) "S"
[1]=>
string(2) " L"
[2]=>
string(2) " M"
}
}
我希望以一种方式连接它的元素,我得到一个有6个元素的数组
array(6) {
[0]=>
string(8) "white, S"
[1]=>
string(8) "white, L"
[2]=>
string(8) "white, M"
[3]=>
string(8) "Black, S"
[4]=>
string(8) "Black, L"
[5]=>
string(8) "Black, M"
}
我尝试了以下但是它不起作用:
$size = 1;
foreach ($attribute_metric as $key => $value) {
$size = $size * sizeof($value);
}
foreach ($attribute_metric as $key => $value) {
if($key > 0){
foreach ($attribute_metric[0] as $subkey => $subvalue) {
array_push($subvalue,$value);
}
}
}
答案 0 :(得分:3)
$array1= $attribute_metric[0]; //['white','black']
$array2= $attribute_metric[1]; // ['S', 'L', 'M']
$resultArray = [];
foreach ($array1 as $color){
foreach ($array2 as $size){
$resultArray[] = $color . ', ' . $size;
}
}
print_r($resultArray);
结果
Array
(
[0] => white, S
[1] => white, L
[2] => white, M
[3] => black, S
[4] => black, L
[5] => black, M
)
答案 1 :(得分:2)
如果原始数组不是太大,那么使用嵌套循环将允许您生成所需的输出。
$colours=array('white','black');
$sizes=array('s','m','l');
$out=array();
foreach( $colours as $colour ){
foreach( $sizes as $size ){
$out[]=$colour.', '.$size;
}
}
print_r( $out );
答案 2 :(得分:1)
试试这个
<?php
$list = array(array('white','Black'), array('S','L','M'));
$result = array();
foreach ($list[0] as $k) {
foreach ($list[1] as $t) {
$result[] = $k.','.$t;
}
}
var_dump($result);
?>
答案 3 :(得分:0)
为了完整起见,如果你想只使用数组函数:
exec bash