使用PHP将对象转换为基于特定键的数组

时间:2016-12-13 12:42:10

标签: php arrays magento object

我对PHP很陌生,我正在努力将一个对象转换为一个数组,以便我可以在我的代码中进一步使用该数组。

我的脚本从Magento API检索产品数据,在结果变量上使用print_r后显示如下结果:

enter image description here

现在我可以看到,这开始于"数组"但是当我尝试对我已分配结果的变量使用echo时,收到错误Catchable fatal error: Object of class stdClass could not be converted to string

如何将对象转换为数组然后拆分数组,以便将所有sku键的值作为数组作为最终结果?

我尝试在结果变量上使用array(),然后尝试使用数组函数对其进行操作,但无论我尝试什么,我都会收到错误,所以我的想法是我没有正确理解这一点

感谢您提供的任何见解。如果您需要查看,我的代码如下:

<?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 个答案:

答案 0 :(得分:1)

如果您只需要将所有skus重写为数组,您可以这样做:

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

像这样漂亮的单行也会起作用:

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

但是如果你真的想要转换一个标准对象或那些数组,那么一个非优雅但又有效且简单的解决方案是将它转换为JSON并返回:

$array = json_decode(json_encode($objects), true);