【问题标题】:Converting Object Into an Array Based on Specific Key with PHP使用 PHP 将对象转换为基于特定键的数组
【发布时间】:2016-12-13 12:42:09
【问题描述】:

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

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

现在我可以看到它以“array”开头,但是当我尝试对已分配结果的变量使用 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];
?>

【问题讨论】:

  • 您正在接收一个对象数组(参见stdClass Object)。所以一个简单的类型转换应该适合你:$array = (array) $zoey_product_list[0];
  • 谢谢,现在这更有意义了 :)

标签: php arrays magento object


【解决方案1】:

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

$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); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    • 2019-03-10
    • 2017-04-30
    • 2015-10-05
    • 2021-07-10
    • 2021-10-14
    • 1970-01-01
    相关资源
    最近更新 更多