我想根据它们所属的类型将以下数组排序并回显到单独的列表中。
Array
(
[0] => Array
(
[itemid] => 1
[itemname] => Sword
[itemtype] => Standard
)
[1] => Array
(
[itemid] => 2
[itemname] => Dagger
[itemtype] => Standard
)
[2] => Array
(
[itemid] => 3
[itemname] => Backpack
[itemtype] => Standard
)
[3] => Array
(
[itemid] => 4
[itemname] => Rope (50ft)
[itemtype] => Standard
)
[4] => Array
(
[itemid] => 5
[itemname] => Tinderbox
[itemtype] => Standard
)
[5] => Array
(
[itemid] => 6
[itemname] => Torch
[itemtype] => Standard
)
[6] => Array
(
[itemid] => 6
[itemname] => Torch
[itemtype] => Standard
)
[7] => Array
(
[itemid] => 6
[itemname] => Torch
[itemtype] => Standard
)
[8] => Array
(
[itemid] => 6
[itemname] => Torch
[itemtype] => Standard
)
[9] => Array
(
[itemid] => 6
[itemname] => Torch
[itemtype] => Standard
)
[10] => Array
(
[itemid] => 8
[itemname] => Bread
[itemtype] => Provisions
)
[11] => Array
(
[itemid] => 8
[itemname] => Bread
[itemtype] => Provisions
)
[12] => Array
(
[itemid] => 8
[itemname] => Bread
[itemtype] => Provisions
)
[13] => Array
(
[itemid] => 8
[itemname] => Bread
[itemtype] => Provisions
)
[14] => Array
(
[itemid] => 8
[itemname] => Bread
[itemtype] => Provisions
)
[15] => Array
(
[itemid] => 8
[itemname] => Bread
[itemtype] => Provisions
)
[16] => Array
(
[itemid] => 8
[itemname] => Bread
[itemtype] => Provisions
)
[17] => Array
(
[itemid] => 8
[itemname] => Bread
[itemtype] => Provisions
)
[18] => Array
(
[itemid] => 9
[itemname] => Healing Salve
[itemtype] => Magical
)
[19] => Array
(
[itemid] => 9
[itemname] => Healing Salve
[itemtype] => Magical
)
)
我想基于itemtype键将其回显到列表中。即:
Standard
=========
Sword Dagger Backpack Rope (50ft) Tinderbox Torch x5
Provisions
=========
Bread x8
Magical
=========
Healing Salve
我尝试这样做无济于事:
foreach ($array as $value) {
if ($value['itemtype'] == 'Standard'){
echo $value['itemname'] . "\n";
}
foreach ($array as $value) {
if ($value['itemtype'] == 'Provisions'){
echo $value['itemname'] . "\n";
}
foreach ($array as $value) {
if ($value['itemtype'] == 'Magical'){
echo $value['itemname'] . "\n";
}
首先将它分成单独的数组可能更明智吗?
答案 0 :(得分:1)
您还可以将项目添加到3个不同的字符串中,并在结尾处回显连接的字符串:
$standard = '';
$provisions = '';
$magical = '';
foreach ($array as $value) {
switch $value['itemtype']{
case 'Standard':
$standard .= $value['itemname'] . "\n";
break;
case 'Provisions':
$provisions .= $value['itemname'] . "\n";
break;
case 'Magical':
$magical .= $value['itemname'] . "\n";
break;
default:
break;
}
}
echo $standard . $provisions . $magical;
因此,您只需要在阵列上循环一次,就可以轻松添加更多案例。