关联数组 - 抓取特定的键和值
Associative arrays - grabbing specific keys and values
我有这个数组:
$items = [
'Mac' => [
'quantity' => $qty1,
'price' => 1899.99
],
'Razer Mouse' => [
'quantity' => $qty2,
'price' => 79.99
],
'WD HDD' => [
'quantity' => $qty3,
'price' => 179.99
],
'Nexus' => [
'quantity' => $qty4,
'price' => 249.99
],
'Drums' => [
'quantity' => $qty5,
'price' => 119.99
]
];
而且我有时只想 select 数量 1 和/或 1899.99,而其他时候我想访问任何其他数量和/或它们的相关价格。
现在我正在尝试:
<?php foreach($items['Mac'] as $x => $x_value): ?>
<p><?= $x_value ?></p>
<?php endforeach ?>
输出:
1
1899.99
1上面是Mac的数量,1899.99是单价,不过我只想要印的数量,两个都不要。
我该怎么做?
只需更改您的 foreach
循环
这个:
<?php
$items = [
'Mac' => [
'quantity' => $qty1,
'price' => 1899.99
],
'Razer Mouse' => [
'quantity' => $qty2,
'price' => 79.99
],
'WD HDD' => [
'quantity' => $qty3,
'price' => 179.99
],
'Nexus' => [
'quantity' => $qty4,
'price' => 249.99
],
'Drums' => [
'quantity' => $qty5,
'price' => 119.99
]
];
foreach($items as $key => $arrVal) {
if($key == 'Mac')
echo $key ."=". $arrVal['quantity'];
}
?>
if(){}
控制要打印的 key
所以如果你想打印
Nexus
只需将值从 Mac
更改为 Nexus
或 smthing 如果你想检查多个,只需使用 ||
像这样 if($key == 'Mac' || $key == 'Nexus')
||
= OR
如果您想获得价格,只需将 $arrVal['quantity'];
更改为 $arrVal['price'];
我有这个数组:
$items = [
'Mac' => [
'quantity' => $qty1,
'price' => 1899.99
],
'Razer Mouse' => [
'quantity' => $qty2,
'price' => 79.99
],
'WD HDD' => [
'quantity' => $qty3,
'price' => 179.99
],
'Nexus' => [
'quantity' => $qty4,
'price' => 249.99
],
'Drums' => [
'quantity' => $qty5,
'price' => 119.99
]
];
而且我有时只想 select 数量 1 和/或 1899.99,而其他时候我想访问任何其他数量和/或它们的相关价格。
现在我正在尝试:
<?php foreach($items['Mac'] as $x => $x_value): ?>
<p><?= $x_value ?></p>
<?php endforeach ?>
输出:
1
1899.99
1上面是Mac的数量,1899.99是单价,不过我只想要印的数量,两个都不要。
我该怎么做?
只需更改您的 foreach
循环
这个:
<?php
$items = [
'Mac' => [
'quantity' => $qty1,
'price' => 1899.99
],
'Razer Mouse' => [
'quantity' => $qty2,
'price' => 79.99
],
'WD HDD' => [
'quantity' => $qty3,
'price' => 179.99
],
'Nexus' => [
'quantity' => $qty4,
'price' => 249.99
],
'Drums' => [
'quantity' => $qty5,
'price' => 119.99
]
];
foreach($items as $key => $arrVal) {
if($key == 'Mac')
echo $key ."=". $arrVal['quantity'];
}
?>
if(){}
控制要打印的 key
所以如果你想打印
Nexus
只需将值从 Mac
更改为 Nexus
或 smthing 如果你想检查多个,只需使用 ||
像这样 if($key == 'Mac' || $key == 'Nexus')
||
= OR
如果您想获得价格,只需将 $arrVal['quantity'];
更改为 $arrVal['price'];