2

I am getting the below mentioned string in my API response. How can I convert this into array?

 "product_options": "{\"info_buyRequest\":{\"qty\":1},\"giftcard_lifetime\":null,\"giftcard_is_redeemable\":0,\"giftcard_email_template\":null,\"giftcard_type\":null}"

Vendor/CustomApi/Model/OrderHistory.php

<?php

namespace Vendor\CustomApi\Model;

use Amos\CustomApi\Api\OrderHistoryInterface;
use Magento\Customer\Model\CustomerFactory;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;

class OrderHistory implements OrderHistoryInterface {

    protected $customerFactory;
    protected $customerRepository;

    public function __construct(CustomerFactory $customerFactory, CustomerRepositoryInterface $customerRepository) {
        $this->customerFactory = $customerFactory;
        $this->customerRepository = $customerRepository;
    }

    public function getOrderHistory($customerId, $direction, $pageSize, $currentPage) {
        try {
            $customer = $this->customerFactory->create()->getCollection()
                    ->addAttributeToSelect("*")
                    ->addAttributeToFilter("entity_id", array("eq" => $customerId));
            $CustomerResult = $customer->getData();
            $customerInfo = $this->customerRepository->getById($customerId);
            $customerAttributeData = $customerInfo->__toArray();
            $VesselId = $customerAttributeData['custom_attributes']['customer_vessels']['value'];
            $customerData = $this->customerFactory->create()->getCollection()
                            ->addAttributeToSelect("*")
                            ->addAttributeToFilter("customer_vessels", array("eq" => $VesselId))
                            ->addAttributeToFilter("group_id", array("eq" => self::GROUP_ID))->load();
            $CustomerDataResult = $customerData->getData();
            $captinId = $CustomerDataResult[0]['entity_id'];
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $order = $objectManager->create('Magento\Sales\Model\Order')->getCollection()->addAttributeToFilter('customer_id', $captinId)->setOrder('entity_id', $direction)->setPageSize($pageSize)->setCurPage($currentPage);
            $orderInfo = $order->getData();
//            print_r($orderInfo);die();
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $orderItemCollection = $objectManager->create('Magento\Sales\Model\ResourceModel\Order\Item\Collection')
                    ->setOrder('entity_id', $direction);

            $orderItemCollection->getSelect()->joinLeft(
                    'sales_order', 'sales_order.entity_id=main_table.order_id', ['increment_id']
            )->where('sales_order.customer_id=?', $captinId);
            $orderResult = $orderItemCollection->getData();
            foreach ($orderInfo as $k => $v) {
                foreach ($orderResult as $k1 => $v1) {
                    if ($v1['order_id'] == $v['entity_id']) {
                        $orderInfo[$k]['product_details'][] = $v1;
                    }
                }
            }
        } catch (\Exception $e) {
            throw new NoSuchEntityException(
            __('Invalid customer.')
            );
        }
        return json_decode($orderInfo);
    }

}

Vendor/CustomApi/Api/OrderHistoryInterface.php

<?php

namespace Vendor\CustomApi\Api;


interface OrderHistoryInterface {
     CONST GROUP_ID = 5;
    /**
     * User can login and once logged in success, user will receive their information with order history.
     * @param int $customerId
     * @param string $direction
     * @param int $pageSize
     * @param int $currentPage
     * @return mixed Order History
     */
    public function getOrderHistory($customerId,$direction,$pageSize,$currentPage);
}
11
  • 1
    have you tried json_decode ? Apr 18, 2019 at 10:44
  • I have tried this but getting error as following: "message": "Class mixed does not exist", "code": -1, Apr 18, 2019 at 10:47
  • please share your code here, it should work with json_decode Apr 18, 2019 at 10:52
  • 2
    I have added my code. Please check. Apr 18, 2019 at 10:59
  • 1
    I am unable to find json_decode in your code Apr 18, 2019 at 11:01

1 Answer 1

3

Just use this below code where you want to convert to array :

/**
 * @var \Magento\Framework\Json\Helper\Data
 */
protected $jsonHelper;

/**
 * [__construct description]
 * @param \Magento\Framework\Json\Helper\Data              $jsonHelper        [description]
 */
public function __construct(
    .......
    \Magento\Framework\Json\Helper\Data $jsonHelper,
    .......
) {
    .......
    $this->jsonHelper = $jsonHelper;
    .......
}

public function yourFunction() {
    $strToArr = $this->jsonHelper->jsonDecode('your data');
    print_r($strToArr);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.