我有一个存储关联数组的对象
对象由
组成class mainObj {
public $name = 0;
public $address = '';
public $someArray = array();
}
这些对象存储在数组中。
objArray[] = obj1;
objArray[] = obj2
我的问题是: 如何才能最好地轻松访问对象内部的关联数组的KEY和VALUE,而该对象本身存储在另一个数组中?
我可以通过迭代获得键和值......
for ($i=0; $i<count($objArray); $i++)
{
$tempArray = $objArray[$i]->someArray;
foreach ($tempArray as $key => $value)
{
echo "Key: $key; Value: $value\n";
}
}
将对象重写为数组在这个阶段可能太有问题......
在PHP中,是否有更快的方法从存储关联数组的对象数组中访问关联数组键和值?
先谢谢你的回答... MARV
答案 0 :(得分:0)
在这种情况下,我会在你的mainObj类中创建一个getter方法,如下所示: -
class mainObj
{
public $name = 0;
public $address = '';
public $someArray = array(1 => 'one' ,2 => 'two', 3 => 'three', 4 => 'four');
public function getSomeArray()
{
return $this->someArray;
}
}
然后您可以非常轻松地访问$someArray
: -
$obj1 = new mainObj();
$obj1->name = 1;
$obj2 = new mainObj();
$obj2->name = 2;
$obj3 = new mainObj();
$obj3->name = 3;
$objArray = array($obj1, $obj2, $obj3);
foreach($objArray as $obj){
echo "Object: {$obj->name}<br/>\n";
foreach($obj->getSomeArray() as $key => $value){
echo "Key: $key , Value: $value<br/>\n";
}
}
输出: -
Object: 1
Key: 1 , Value: one
Key: 2 , Value: two
Key: 3 , Value: three
Key: 4 , Value: four
Object: 2
Key: 1 , Value: one
Key: 2 , Value: two
Key: 3 , Value: three
Key: 4 , Value: four
Object: 3
Key: 1 , Value: one
Key: 2 , Value: two
Key: 3 , Value: three
Key: 4 , Value: four
答案 1 :(得分:0)
以下是您想要的:
foreach ($objArray as $key => $value){
foreach ($value->someArray as $key => $value){
echo "Key: $key; Value: $value\n";
}
}
然而,假设有如下结构。如果您的结构不同,您需要尝试稍微不同的方法:
Array
(
[0] => mainObj Object
(
[someArray] => Array
(
[0] => 3
[1] => 4
[2] => 5
)
)
[1] => mainObj Object
(
[someArray] => Array
(
[0] => 6
[1] => 7
[2] => 8
)
)
[2] => mainObj Object
(
[someArray] => Array
(
[0] => 9
[1] => 20
[2] => 11
)
)
)