Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Object Into an Array Based on Specific Key with PHP

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];
?>

1 Answers

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); 
like image 136
Bartosz Zasada Avatar answered May 30 '26 05:05

Bartosz Zasada



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!