[英]echo a multi-dimensional associative array into lists based on key value
我想根據它們是哪種項目類型對以下數組進行排序和回顯到單獨的列表中。
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";
}
首先將其拆分成單獨的數組也許更明智?
您還可以將項目添加到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;
因此,您只需要在數組上循環一次,就可以輕松添加更多的案例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.