我在PHP中有这一块代码(它只是从API检索一些交付方式,API是第三方)
use MPAPI\Services\DeliveryMethods;
use MPAPI\Services\Deliveries;
use MPAPI\Entity\PartnerDelivery;
use MPAPI\Entity\GeneralDelivery;
$deliveryMethods = new DeliveryMethods($mpapiClient);
$response = $deliveryMethods->get();
var_dump($response);
响应是:
array(2) {
[0]=>
object(MPAPI\Entity\DeliveryMethod)#35 (1) {
["data":protected]=>
array(7) {
["id"]=>
string(4) "Test"
["title"]=>
string(18) "Testovacia doprava"
["price"]=>
int(10)
["cod_price"]=>
int(10)
["free_limit"]=>
int(0)
["delivery_delay"]=>
int(5)
["is_pickup_point"]=>
bool(false)
}
}
[1]=>
object(MPAPI\Entity\DeliveryMethod)#36 (1) {
["data":protected]=>
array(7) {
["id"]=>
string(3) "UPS"
["title"]=>
string(22) "Kuriérska služba UPS"
["price"]=>
int(5)
["cod_price"]=>
int(0)
["free_limit"]=>
int(0)
["delivery_delay"]=>
int(4)
["is_pickup_point"]=>
bool(false)
}
}
}
我想在PHP中访问它,所以我的foreach循环看起来像:
<?php foreach ($response[0]->data as $item) { ?>
// ...
<?php } ?>
但是我收到了一个错误:
致命错误:未捕获错误:无法访问受保护的属性 MPAPI \ Entity \ DeliveryMethod :: $ data in /data/web/virtuals/175241/virtual/www/doprava.php:39堆栈跟踪:#0 {main}抛出/data/web/virtuals/175241/virtual/www/doprava.php 第39行
那么如何在PHP中正确读取这些数据?
如果我改变这样的foreach循环:
<?php foreach ($response as $item) { ?>
// ...
<?php } ?>
我会收到另一个错误:
致命错误:未捕获错误:无法使用类型对象 MPAPI \ Entity \ DeliveryMethod作为数组
在API的文档中,没有关于https://github.com/mallgroup/mpapi-client-php/blob/master/doc/DELIVERIES.md
的内容答案 0 :(得分:0)
我同意你的意见,文件对此并不太清楚。
如果查看the source,您会发现类MPAPI\Entity\DeliveryMethod
具有此方法,该方法将数据作为数组返回:
/**
* @see \MPAPI\Entity\AbstractEntity::getData()
*/
public function getData()
{
return [
self::KEY_ID => $this->getId(),
self::KEY_TITLE => $this->getTitle(),
self::KEY_PRICE => $this->getPrice(),
self::KEY_COD_PRICE => $this->getCodPrice(),
self::KEY_FREE_LIMIT => $this->getFreeLimit(),
self::KEY_DELIVERY_DELAY => $this->getDeliveryDelay(),
self::KEY_PICKUP_POINT => $this->isPickupPoint()
];
}
所以,你会做这样的事情
<?php
$methodList = $deliveryMethods->get();
foreach ($methodList as $method) {
$methodData = $method->getData();
// OR
$methodTitle = $method->getTitle()
// ...
}
?>