我正在尝试创建一个具有两个属性的数组并遍历它。 但是我不知道该怎么做。
在此示例中,一个属性:
$foodArray = ["apple", "banana"];
foreach ($foodArray as $food) {
echo $food ."<br />";
}
现在,我要添加数组-绿色代表苹果,黄色代表香蕉,并以相同的方式循环。如何以最佳方式做到这一点?
答案 0 :(得分:3)
您可以通过在子数组中添加多个元素来添加多个属性
$foodArray = [['name' => 'Apple', 'color' => 'Yellow'],
['name' => 'Banana', 'color' => 'yellow']];
foreach($foodArray as $fruit) {
echo $fruit['name']." - ".$fruit['color']." <br />";
}
或者,如果仅需要这两个属性,则可以将键用作名称,将值用作颜色。
$foodArray = ['Apple' => 'green', 'Banana' => 'yellow'];
foreach($foodArray as $fruit => $color) {
echo $fruit." - ".$color ." <br />";
}
答案 1 :(得分:2)
要遍历多个属性,您需要使用多维数组。
基本概念是数组应包含数组。
现在这些数组可以具有多个属性。
您需要获取键值对。
因此,您的数组将是:
$foodArray = ['green' => 'apple', 'yellow' => 'banana'];
foreach ($foodArray as $foodColor => $food) {
echo $foodColor . ' = ' $food ."<br />";
}
否则,您可以定义多维数组并在其上循环:
$foodArray = [];
$foodArray['apple']['name'] = ['apple'];
$foodArray['apple']['color'] = ['green'];
$foodArray['banana']['name'] = ['banana'];
$foodArray['banana']['color'] = ['yellow'];
然后遍历它。
foreach ($foodArray as $food) {
echo $food['color'] . ' = ' $food['name'] ."<br />";
}
每个食品都可以具有多个属性,因为它是一个多维数组。
答案 2 :(得分:2)
使用此方法,您可以添加其他属性
$foodArray = [
[
'name' => 'apple',
'color' => 'green',
],
[
'name' => 'banana',
'color' => 'yellow',
]
];
//loop
foreach($foodArray as $food) {
echo $food['name'] . ' have color ' . $food['color'];
}
答案 3 :(得分:2)
如果要使用数组存储多个属性,则使用多维数组的下一种方法可能会有所帮助:
<?php
$foodArray = array(
"apple" => array(
"color" => "green",
"size" => "small"
),
"banana" => array(
"color" => "yellow",
"size" => "medium"
)
);
foreach ($foodArray as $fruit => $properties) {
echo $fruit."<br />";
foreach ($properties as $key => $value) {
echo $key.": ".$value."<br />";
}
echo "<br />";
}
?>
输出:
apple
color: green
size: small
banana
color: yellow
size: medium
答案 4 :(得分:1)
您可以执行以下操作:
//keyed array
$foodArray = ['apple' => 'green', 'banana' => 'yellow'];
// loop through array as key/value prop
foreach($foodArray as $fruit => $color) {
echo $fruit." - ".$color ." <br />";
}
答案 5 :(得分:1)
您的一个属性数组
$foodArray = ["apple", "banana"];
新数组可在第一个数组中添加键
$key_array = ["green", "yellow"];
现在用绿色->苹果,黄色->香蕉创建数组
$output = array_combine($key_array, $foodArray);