我正在整理我在工作中遇到的一些旧代码,包括我想将其组合成嵌套数组的各种数组,并且想知道一种循环遍历嵌套数组内容的简单方法(可能首先,有比嵌套数组更好的数据存储方式,如果是这样,欢迎提出建议)。
以下代码只是原始代码结构的示例,其行为方式与一般化输出相同。
$someArray 元素过去是单独定义的,这似乎非常耗时,因此我想更改它:
$fruit['fruit']['apple']['size'] = 'small';
$fruit['fruit']['apple']['colour'] = 'red';
$fruit['fruit']['apple']['taste'] = 'bitter';
$fruit['fruit']['pear']['size'] = 'big';
$fruit['fruit']['pear']['colour'] = 'green';
$fruit['fruit']['pear']['taste'] = 'sweet';
这是我正在构建的嵌套数组的示例:
class someEntity
{
public function someFunction()
{
$someArray = array
(
'apple' => array(
'size' => 'small',
'colour' => 'red',
'taste' => 'bitter'
),
'pear' => array(
'size' => 'big',
'colour' => 'green',
'taste' => 'sweet'
)
);
return($someArray);
}
public function anotherFunction()
{
# some other stuff
}
}
通过foreach循环调用:
$someArray= someEntity::someFunction();
var_dump($someArray);
foreach($someArray as $key)
{
foreach($key as $key => $value)
{
print($key.': '.$value.'<br>');
}
}
array (size=2)
'apple' =>
array (size=3)
'size' => string 'small' (length=5)
'colour' => string 'red' (length=3)
'taste' => string 'bitter' (length=6)
'pear' =>
array (size=3)
'size' => string 'big' (length=3)
'colour' => string 'green' (length=5)
'taste' => string 'sweet' (length=5)
输出:
尺寸:小 颜色:红色 味道:苦 尺寸:大 颜色:绿色 味道:甜
问题:
- 压缩 $fruits 数组的最佳方法是什么?我的 $someArray 方法不正确吗?
- 有没有更好的方法来调用 $someArray 数据而不需要嵌套的 foreach 循环?
考虑:
- 嵌套数组可能会变得更复杂,可能还有一层更深
- 不想在这种情况下使用数据库
提前致谢
已更新
我使用对象进行了如下修改。
class fruit
{
private $_type;
private $_size;
private $_colour;
private $_taste;
public function __construct($type,$size,$colour,$taste)
{
$this->_type = $type;
$this->_size = $size;
$this->_colour = $colour;
$this->_taste = $taste;
}
public function displayFruitData()
{
echo'<br>'.$this->_type.'<br>'.$this->_size.'<br>'.$this->_colour.'<br>'.$this->_taste.'<br><br>';
}
}
$fruit1 = new fruit("apple","small","red","bitter");
$fruit2 = new fruit("pear","medium","yellow","sweet");
$fruit3 = new fruit("pineapple","large","brown","sweet");
$output = $fruit1->displayFruitData();
$output = $fruit2->displayFruitData();
$output = $fruit3->displayFruitData();
exit();
最佳答案
你可以像这样简单地做到这一点
<?php
$fruits = array('apple', 'pear');
$size = array('apple' => 'small', 'pear' => 'big');
$colour = array('apple' => 'red', 'pear' => 'green');
$taste = array('apple' => 'bitter', 'pear' => 'sweet');
foreach($fruits as $fruit)
{
echo "$fruit Size is {$size[$fruit]}<br />";
echo "$fruit Colour is {$colour[$fruit]}<br />";
echo "$fruit Taste is {$taste[$fruit]}<br />";
echo '<br />';
}
?>
输出
apple Size is small
apple Colour is red
apple Taste is bitter
pear Size is big
pear Colour is green
pear Taste is sweet
关于PHP:访问嵌套数组元素的有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15851499/