2016-03-21 118 views
0

我連接到一個API,該API返回此嵌套對象值。foreach嵌套對象php

我該如何迭代每個[「number:protected」]?這對我來說是新東西,我只想返回「number:protected」。

Array 
(
[0] => SDK2go\seat2go Object 
    (
     [status:protected] => Vacant 
     [number:protected] => D,10,A,STR3,ROOM 
     [passenger:protected] => 
     [price:protected] => 
    ) 

[1] => SDK2go\seat2go Object 
    (
     [status:protected] => Vacant 
     [number:protected] => D,15,A,STR3,ROOM 
     [passenger:protected] => 
     [price:protected] => 
    ) 

[2] => SDK2go\seat2go Object 
    (
     [status:protected] => Vacant 
     [number:protected] => D,16,A,STR3,ROOM 
     [passenger:protected] => 
     [price:protected] => 
    ) 

[3] => SDK2go\seat2go Object 
    (
     [status:protected] => Vacant 
     [number:protected] => D,17,A,STR3,ROOM 
     [passenger:protected] => 
     [price:protected] => 
    ) 

[4] => SDK2go\seat2go Object 
    (
     [status:protected] => Vacant 
     [number:protected] => D,18,A,STR3,ROOM 
     [passenger:protected] => 
     [price:protected] => 
    ) 

[5] => SDK2go\seat2go Object 
    (
     [status:protected] => Vacant 
     [number:protected] => D,19,A,STR3,ROOM 
     [passenger:protected] => 
     [price:protected] => 
    ) 

) 

我有一些,但沒有結果表明:

foreach($sList as $list){ 
    echo $list['number:protected']; 
} 

請幫助。提前致謝。

+2

'SDK2go \ seat2go'類是怎麼樣的?有沒有'getNumber()'方法內?如果是的話,就像'$ list-> getNumber()'一樣調用它。你應該搜索任何公共方法來查看要使用什麼.. –

+1

這些是對象數組中的名稱空間類的實例。您正嘗試訪問類中的受保護屬性。這不會是一個選項,因爲受保護的屬性.. ..保護..檢查了這一點:http://stackoverflow.com/questions/4361553/php-public-private-protected ...作爲@MateiMihai上面提到的,應該成爲一個_「getter」_方法,它可以讓你獲得這些屬性。 – CodeGodie

+0

好了。 .echo $ obj-> getNumber(); – user3651476

回答

0

因此,這裏發生的事情是,您的API正在以數組內的對象形式返回一個類的實例。要模仿它看看下面的代碼:

<?php 

namespace SDK2go; 

class seat2go 
{ 
    protected $status; 
    protected $number; 
    protected $passenger; 
    protected $price; 

    public function __construct($status, $number) 
    { 
     $this->status = $status; 
     $this->number = $number; 
    } 

    public function get_status() 
    { 
     echo $this->status; 
    } 

    public function get_number() 
    { 
     echo $this->number; 
    } 
} 

$arr = array(
    new seat2go("Vacant", "D,10,A,STR3,ROOM"), 
    new seat2go("Vacant", "D,15,A,STR3,ROOM"), 
    new seat2go("Vacant", "D,16,A,STR3,ROOM") 
); 


echo "<pre>"; 
print_r($arr); 
echo "</pre>"; 

以上將給你你有print_r結果。因此,爲了訪問這些屬性,您必須調用類應該具有的getter函數。因爲如此:

foreach ($arr as $a) { 
    echo $a->get_status(); 
    echo $a->get_number(); 
} 

希望這有助於。