3

I'm quite new to PHP and I'm struggling converting an object into an array so that I can use that array in my code further down the line.

My script retrieves product data from the Magento API which shows as the following result after using print_r on the result variable:

enter image description here

Now I can see that this begins with "array" but when I try to use echo on the variable that I have assigned the result to, I receive the error Catchable fatal error: Object of class stdClass could not be converted to string.

How can I convert the object to an array and then split the array so that I have the values of all of the sku keys as an array as my eventual result?

I've tried using array() on the result variable and then attempted to manipulate it using array functions but no matter what I try I am receiving errors, so my thought is that I am not understanding this correctly.

Thank you for any insight that you can offer. My code is below if you need to see it:

<?php
    // Global variables.
    $client = new SoapClient('xxx'); // Magento API URL.
    $session_id = $client->login('xxx', 'xxx'); // API Username and API Key.

    // Filter where the 'FMA Stock' attribute is set to 'Yes'.
    $fma_stock_filter = array('complex_filter'=>
        array(
            array('key'=>'fma_stock', 'value'=>array('key' =>'eq', 'value' => 'Yes')),
        ),
    );

    // Assign the list of products to $zoey_product_list.
    $zoey_product_list = $client->catalogProductList($session_id, $fma_stock_filter);

    echo $zoey_product_list[0];
?>
2
  • 1
    You are receiving an array of objects (see the stdClass Object). So a simple type cast should work for your: $array = (array) $zoey_product_list[0]; Commented Dec 13, 2016 at 12:45
  • Thank you, this makes a lot more sense now :) Commented Dec 13, 2016 at 12:52

1 Answer 1

1

If all you need is to rewrite all skus into an array, you can just do it like this:

$skus = [];
foreach ($items as $item) { // not sure which variable from your code contains print_r'd data, so assuming $items
    $skus[] = $item->sku;
}

A nice one-liner like this will also work:

$skus = array_map(function($item) { return $item->sku; }, $items);

But if you actually want to convert a standard object, or an array of those, a non-elegant yet working and simple solution is to convert it to JSON and back:

$array = json_decode(json_encode($objects), true); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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