我想创建此输出:
LG LG#Spain LG#Spain#Paypal LG#Spain#Paypal#Male LG#Spain#Paypal#Female LG#Spain#CCard LG#Spain#CCard#Male LG#Spain#CCard#Female LG#Croatia LG#Croatia#Paypal LG#Croatia#Paypal#Male LG#Croatia#Paypal#Female LG#Croatia#CCard LG#Croatia#CCard#Male LG#Croatia#CCard#Female LG#Czech LG#Czech#Paypal LG#Czech#Paypal#Male LG#Czech#Paypal#Female LG#Czech#CCard LG#Czech#CCard#Male LG#Czech#CCard#Female Sony Sony#Spain Sony#Spain#Paypal Sony#Spain#Paypal#Male Sony#Spain#Paypal#Female Sony#Spain#CCard Sony#Spain#CCard#Male Sony#Spain#CCard#Female Sony#Croatia Sony#Croatia#Paypal Sony#Croatia#Paypal#Male Sony#Croatia#Paypal#Female Sony#Croatia#CCard Sony#Croatia#CCard#Male Sony#Croatia#CCard#Female Sony#Czech Sony#Czech#Paypal Sony#Czech#Paypal#Male Sony#Czech#Paypal#Female Sony#Czech#CCard Sony#Czech#CCard#Male Sony#Czech#CCard#Female
和我的代码:
<?php
$delimiter = '#';
$keys = ['Brand','Country','Method','Gender'];
$arr[$keys[0]] = ['LG','Sony'];
$arr[$keys[1]] = ['Spain','Croatia','Czech'];
$arr[$keys[2]] = ['Paypal','CCard'];
$arr[$keys[3]] = ['Male','Female'];
$sizeofdims = sizeof($keys);
$main_key = $keys[0];
echo '<pre>';
foreach ($arr[$main_key] as $main_item)
{
$key_handle = $main_item;
echo "$key_handle\n";
foreach ($keys as $i=>$k)
{
if ($k == $main_key)
{
continue;
}
foreach ($arr[$k] as $item)
{
$key_current = $key_handle;
$key_handle .= $delimiter.$item;
echo "$key_handle\n";
if ($i+1 == $sizeofdims)
{
$key_handle = $key_current;
}
else
{
break;
}
}
}
}
echo '</pre>';
当前输出:
LG LG#Spain LG#Spain#Paypal LG#Spain#Paypal#Male LG#Spain#Paypal#Female Sony Sony#Spain Sony#Spain#Paypal Sony#Spain#Paypal#Male Sony#Spain#Paypal#Female
答案 0 :(得分:0)
为了开个玩笑,我会给出一个最简单的解决方案:
foreach ($arr[$keys[0]] as $brand) {
echo $brand . "\n";
foreach ($arr[$keys[1]] as $country) {
echo $brand . '#' . $country . "\n";
foreach ($arr[$keys[2]] as $method) {
echo $brand . '#' . $country . '#' . $method . "\n";
}
}
}
但下次自己尝试一下。
答案 1 :(得分:0)
您的阵列有点难以使用。我建议将它重新组织成一个多维数组。
$array = array(
'LG' => array(
'Neverland' => array('Pirate gold', 'Magic coins', 'Fairy dust'), ), )
'Fantasia' => array('Gems', 'Dragon Heartstring', 'Old underwear'), ),
),
'Sony' => array(
'Neverland' => array('Pirate gold', 'Magic coins', 'Fairy dust'), ), )
'Fantasia' => array('Gems', 'Dragon Heartstring', 'Old underwear'), ),
),
);
现在你可以进行以下循环
foreach ($array as $brand => $countries) {
echo $brand."<br />";
foreach ($countries as $country => $paymentMethods) {
echo $brand."#".$country."<br />";
foreach ($paymentMethods as $paymentMethod) {
echo $brand."#".$country."#".$paymentMethod."<br />";
}
}
}