Php foreach嵌套对象
我正在连接一个返回这个嵌套对象值的API 如何迭代每个[“编号:受保护”]?这对我来说是新鲜事,我只想返回“编号:protected” 我有一些东西,但什么也没有显示:Php foreach嵌套对象,php,arrays,object,Php,Arrays,Object,我正在连接一个返回这个嵌套对象值的API 如何迭代每个[“编号:受保护”]?这对我来说是新鲜事,我只想返回“编号:protected” 我有一些东西,但什么也没有显示: foreach($sList as $list){ echo $list['number:protected']; } 请帮忙。提前感谢。所以这里发生的事情是,您的API在数组中以对象形式返回类的实例。要模拟它,请查看以下代码: <?php namespace SDK2go; class seat
foreach($sList as $list){
echo $list['number:protected'];
}
请帮忙。提前感谢。所以这里发生的事情是,您的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>";
希望这有帮助。SDK2go\seat2go类的外观如何?其中是否有
getNumber()
方法?如果是这样,请像$list->getNumber()
那样调用它。。您应该搜索任何公共方法以查看要使用的内容。这些是对象数组中命名空间类的实例。您正在尝试访问类中受保护的属性。这将不是一个选项,因为受保护的属性是。。保护得很好。。看看这个:。。。正如上面提到的@MateiMihai,应该有一个“getter”方法来允许您获取这些属性。echo$obj->getNumber();
<?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>";
foreach ($arr as $a) {
echo $a->get_status();
echo $a->get_number();
}