0

我有一个存储关联数组的对象

对象包括

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

4

2 回答 2

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
于 2013-07-27T14:25:39.443 回答
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
                )
        )
)
于 2013-07-27T14:48:46.857 回答