我想在一行中回顯3個信息,並且可能有多行。所有這些3個信息都來自不同的陣列或重疊陣列。PHP在一行中回顯多個結果。合併Foreach /開關
最終期望的結果:
PET1(如果有的話)Attrib1(如果有的話)Attrib2(如果有的話)
PET2(如果有的話)Attrib1(如果有的話)Attrib2(如果有的話)
PET3(如果有的話)Attrib1(如果有的話)Attrib2(如果有的話)
併發症發生的位置的結果,其中所述寵物,Attrib1和Attrib2是高度雜物並且取決於用戶的輸入。它們中的任何一個可能完全顯示或爲空。
我設法使用開關將Pet和Attrib1拉到一起。但是爲了迴應Attrib2,我應該使用另一個開關(下面的方框2)。我如何將它們全部合併成一行一列(即Pet Attrib1 Attrib2)?
// This specifies which row it should display
// Each of the following $xxxRow contains information about the Row position in another array
// Didn't include the Row array here to simplify my question
$Display_Position = array (
'Crocs' => $CrocsRow, 'Cat' => $CatRow, 'Rhino' => $RhinoRow, 'Wolf' => $WolfRow, 'Hyena' => $HyenaRow, 'Lion' => $LionRow, 'Tiger' => $TigerRow, 'Dingo' => $DingoRow, 'Bear' => $BearRow);
// ------------------
$Assign_Attributes = array (
'US'=>
array ('Wolf'=>'Strong', 'Dingo'=>'Healthy', 'Tiger'=>'Fast', 'Cat'=>'Timid'),
'Africa'=>
array ('Tiger'=>'Strong', 'Hyena'=>'Healthy', 'Crocs'=>'Fast', 'Rhino'=>'Timid'),
'Asia'=>
array ('Cat'=>'Strong', 'Wolf'=>'Healthy', 'Crocs'=>'Fast', 'Hynena'=>'Timid'),
'Ocenia'=>
array ('Bear'=>'Strong', 'Crocs'=>'Healthy', 'Cat'=>'Fast', 'Dingo'=>'Timid'),
);
// ------------------
$colA // to display column position, comes from another array and not included here
$rowA // to display row position, comes from another array and not included here
// ------------------
// BLOCK 1: $_Pets with its assigned attributes
// Success. Managed to display $_Pets with the $Assign_Attributes
// This will display either "Tiger (if any)" or "Tiger (if any) Strong (if any)" in the same row/column
foreach ($Display_Position as $_Pets => $_PetsLoc){
if ($_PetsLoc = $rowA) {
$Attrib = $Assign_Attributes ['Africa'][$_Pets]; // Africa is an eg. It actually is $colA
switch ($Attrib) {
case 'Strong':
echo $_Pets.'Strong<br/ >'; break;
case 'Healthy':
echo $_Pets.'Healthy<br/ >'; break;
case 'Fast':
echo $_Pets.'Fast<br/ >'; break;
case 'Timid':
echo $_Pets.'Timid<br/ >'; break;
default:
echo $_Pets.'<br/ >';
break;
}
}
}
// ------------------
// BLOCK 2: Attributes 2
// Block 2 should desirable be merged with BLOCK 1.
// Example: This will eventually display either "Tiger (if any)" or "Tiger Timid (if any)"
// Right now, i'm using CSS to work around for the display of Block 2, which is messy
foreach ($Display_Position as $_Pets => $_PetsLoc){
if ($_PetsLoc = $rowA) {
$Attrib2 = $Assign_Attributes ['Africa'][$_Pets]; // Africa is an eg. It actually is $colA
switch ($Attrib2) {
case 'Strong':
echo 'Strong2<br/ >';break;
case 'Healthy':
echo 'Healthy2<br/ >';break;
case 'Fast':
echo 'Fast2<br/ >';break;
case 'Timid':
echo 'Timid2<br/ >';break;
}
}
}
這太複雜了嗎?對我的水平來說這絕對是具有挑戰性的。當有多個Switch時,是否還有其他PHP技巧可以做得更好?
您真的想在if條件中將'$ _PetsLoc'賦值給'$ rowA'嗎? – Spell
你的意思是輸出應該顯示如:「Crocs Strong Healthy」? –
@MahavirMunot沒錯。它也可以是鱷魚強壯的Strong2或Crocs空的空或空什麼都沒有顯示空的空空 – Mike