2013-07-27 36 views
0

我有其中存儲關聯數組PHP訪問值,可以快速的Arrray持物,其中對象中的一個元件具有一個數組

目的包括

class mainObj { 
public $name = 0; 
public $address = ''; 
public $someArray = array(); 
    } 

這些對象存儲在一個對象陣列。

objArray[] = obj1; 
objArray[] = obj2 

我的問題是: 我最好,很容易如何可以訪問它本身存儲在另一個數組對象內部的關聯數組的鍵和值?

我可以回去通過迭代得到鍵和值...

for ($i=0; $i<count($objArray); $i++) 
{ 
$tempArray = $objArray[$i]->someArray; 
    foreach ($tempArray as $key => $value) 
    { 
     echo "Key: $key; Value: $value\n"; 
    } 
    } 

重新編寫的對象是一個數組在這個階段可能是問題太多......

在PHP中,有沒有更快的方法來訪問存儲關聯數組的對象數組中的關聯數組鍵和值?

衷心感謝你對你的答案提前... 馬福

+0

'$ objArray [$ i] - > someArray [$ key];'? –

+0

對不起,如果這個問題冒犯了你......也許我可以稍微說一下這個問題......我在第一時間發佈問題之前嘗試了你的建議,它並沒有給我一個數組或值的關鍵,這就是我首先提出這個問題的原因。 – Marv

+0

你可以實現[ArrayAccess](http://www.php.net/manual/en/class.arrayaccess.php) – bitWorking

回答

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 
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 
       ) 
     ) 
) 
相關問題