我的关联数组:
$products = array();
$products[101] = array(
"name" => "Red Shirt",
"img" => "img/shirts/shirt-101.jpg",
"price" => 18
);
$products[102] = array(
"name" => "Black Shirt",
"img" => "img/shirts/shirt-102.jpg",
"price" => 20
);
$products[103] = array(
"name" => "Blue Shirt",
"img" => "img/shirts/shirt-103.jpg",
"price" => 20
);
所以我想说我想输出所有产品数组的名称,如下所示:
红衬衫,黑衬衫,蓝衬衫
如何通过foreach循环实现这一目标?我试图一次只输出所有数组中的特定键,但是如果不输出所有键,我似乎无法做到。
还可以说我想输出某个数组的“价格”,比如$ products [103]我该如何实现呢?
谢谢!
答案 0 :(得分:4)
您可以使用以下代码,使用foreach
foreach($products as $pro)
{
echo $pro['name'];
}
上面的代码只会打印产品数组的name
键
获取$product['103']
的价格,您可以使用如下代码
foreach ($products as $key => $value)
{
if ($key == '103')
{
echo $pro['price'];
}
}
编辑:获取名称数组
$names = array();
foreach ($products as $pro)
{
$names[] = $pro['name'];
}
print_r($names);
它会返回
数组([0] =>红衬衫[1] =>黑衬衫[2] =>蓝衬衫)
让我知道这是否有助于你
答案 1 :(得分:1)
简单,像这样使用
foreach($products as $product){
echo $product['name'];
}
答案 2 :(得分:1)
试试这个
foreach($products as $key => $val) {
// For name
echo $val['name'];
// For specific product price
if($key == 103) {
echo $val['price'];
}
}
如果有任何问题,请告诉我。
答案 3 :(得分:1)
请尝试以下代码(这将涵盖所有方案):
function getMyArray($key, $arr = array()){
$result = array();
foreach($arr as $arrVal){
$result[] = $arrVal[$key];
}
return implode(", ", $result);
}
echo getMyArray('name', $products); // Red Shirt, Black Shirt, Blue Shirt
echo getMyArray('img', $products); //path1, path2, path3
echo getMyArray('price', $products); // 18, 20, 20
如果你想要一些特定的价值:
echo $products[103]['price']; // 20
答案 4 :(得分:0)
试试这个
foreach ($products as $prd) {
echo $prd['name'];
}
答案 5 :(得分:0)
$productNames = array();
foreach($products as $key=>$product) {
$productNames[] = $product['name'];
}
//all names with comma
echo implode(',',$productNames);
echo "\n";
//only price of $products[103]
echo $products[103]['price'];
<强>结果:强>
Red Shirt, Black Shirt, Blue Shirt
20
答案 6 :(得分:0)
您将获得与此代码所希望的完全相同的输出
foreach($products as $key=>$result)
{
echo $result['name'].', ';
}
Out put:
Red Shirt, Black Shirt, Blue Shirt