I have this chunk of code in PHP (it just retrieve some delivery methotds from API, API is 3rd party)
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);
And response is:
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)
}
}
}
I would like to access it in PHP, so my foreach loop looks like:
<?php foreach ($response[0]->data as $item) { ?>
// ...
<?php } ?>
But I get an error:
Fatal error: Uncaught Error: Cannot access protected property MPAPI\\Entity\\DeliveryMethod::$data in /data/web/virtuals/175241/virtual/www/doprava.php:39 Stack trace: #0 {main} thrown in /data/web/virtuals/175241/virtual/www/doprava.php on line 39
So how to correctly read this data in PHP?
If I change foreach loop like this:
<?php foreach ($response as $item) { ?>
// ...
<?php } ?>
I will get another error:
Fatal error: Uncaught Error: Cannot use object of type MPAPI\\Entity\\DeliveryMethod as array
At API's documentation there is nothing about that https://github.com/mallgroup/mpapi-client-php/blob/master/doc/DELIVERIES.md
I agree with you, the documentation is not too clear about that. If you look at the source , you can see that the class MPAPI\\Entity\\DeliveryMethod
has this method which returns the data as an array :
/**
* @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()
];
}
So, you would do something like this
<?php
$methodList = $deliveryMethods->get();
foreach ($methodList as $method) {
$methodData = $method->getData();
// OR
$methodTitle = $method->getTitle()
// ...
}
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.