草庐IT

php - 将对象转换为关联数组返回空值

coder 2024-05-02 原文

我正在调用一个 magento soap v2 api 并作为返回得到一个对象的响应,我试图在关联数组中转换该对象。但是当我尝试使用 json 编码/解码方法执行此操作时,它返回一个空数组。

$result = Magento::call()->catalogProductList();
$array = json_decode(json_encode($result), true);

1)对象不为空。 2) 类型转换对我来说不是一个选项,因为我试图避免在前面加上 *。

更新

这是我尝试编码的结果值。

    Tinyrocket\Magento\Objects\MagentoObjectCollection Object
    (
        [collection:protected] => Array
            (
                [0] => Tinyrocket\Magento\Objects\MagentoObject Object
                    (
                        [data:protected] => Array
                            (
                                [product_id] => 9
                                [sku] => Tilapia
                                [name] => Tilapia
                                [set] => 4
                                [type] => simple
                                [category_ids] => Array
                                    (
                                        [0] => 2
                                        [1] => 4
                                    )

                                [website_ids] => Array
                                    (
                                        [0] => 1
                                    )

                            )

                    )

                [1] => Tinyrocket\Magento\Objects\MagentoObject Object
                    (
                        [data:protected] => Array
                            (
                                [product_id] => 10
                                [sku] => Deshi Rui
                                [name] => Deshi Rui
                                [set] => 4
                                [type] => simple
                                [category_ids] => Array
                                    (
                                        [0] => 2
                                        [1] => 4
                                    )

                                [website_ids] => Array
                                    (
                                        [0] => 1
                                    )

                            )

                    )

...
...

更新 2

var_export($result) 的输出

Tinyrocket\Magento\Objects\MagentoObjectCollection::__set_state(array(
   'collection' => 
  array (
    0 => 
    Tinyrocket\Magento\Objects\MagentoObject::__set_state(array(
       'data' => 
      array (
        'product_id' => '9',
        'sku' => 'Tilapia',
        'name' => 'Tilapia',
        'set' => '4',
        'type' => 'simple',
        'category_ids' => 
        array (
          0 => '2',
          1 => '4',
        ),
        'website_ids' => 
        array (
          0 => '1',
        ),
      ),
    )),
    1 => 
    Tinyrocket\Magento\Objects\MagentoObject::__set_state(array(
       'data' => 
      array (
        'product_id' => '10',
        'sku' => 'Deshi Rui',
        'name' => 'Deshi Rui',
        'set' => '4',
        'type' => 'simple',
        'category_ids' => 
        array (
          0 => '2',
          1 => '4',
        ),
        'website_ids' => 
        array (
          0 => '1',
        ),
      ),
    )),

   'count' => 2,
))

最佳答案

json_encode 将您的对象相应地转换为其属性的可见性。

因为 Tinyrocket\Magento\Objects\MagentoObjectCollection$collection 是一个 protected 属性,它的值不会被 json_encode 读取。

对于这个问题我有两个解决方案,其中一个需要修改 Magento 的源代码,所以我不推荐它,因为它可能会产生错误,或者每次更新 CMS 时都会中断。


第一个解决方案使用 Reflection ,因此您将需要 PHP 5,这应该不是问题,因为 Magento needs PHP 5.4 .

以下函数循环遍历 \Tinyrocket\Magento\Objects\MagentoObjectCollection 对象以读取所有属性,并返回一个数组。

function magentoObjectCollectionToArray(\Tinyrocket\Magento\Objects\MagentoObjectCollection $object)
{
    // The basic structure of your array.
    $array = array(
        'collection' => array()
    );

    // Since $collection is a protected property, we need to reflect it to read the value.
    $collection_reflection = new \ReflectionProperty('\Tinyrocket\Magento\Objects\MagentoObjectCollection', 'collection');
    // This method allows you to read protected and private properties for the current ReflectionProperty object.
    $collection_reflection->setAccessible(true);

    // Now we need to loop through all objects...
    foreach ($collection_reflection->getValue($object) as $property => $value)
    {
        // Two cases : either a \Tinyrocket\Magento\Objects\MagentoObject object, or the $count property.
        if ($value instanceof \Tinyrocket\Magento\Objects\MagentoObject)
        {
            // Same here, since $data is also a protected property, we need to reflect it.
            $data_reflection = new \ReflectionProperty('\Tinyrocket\Magento\Objects\MagentoObject', 'data');
            $data_reflection->setAccessible(true);

            $array['collection'][$property] = array(
                'data' => $data_reflection->getValue($value)
            );
        }
        else
        {
            // We don't forget the $count property.
            $array['collection'][$property] = $value;
        }
    }

    // And you have your array without using JSON.
    return $array;
}

PHP 文档链接:


第二种解决方案使用JsonSerializable ,因此您将需要 PHP 5.4,这也不成问题。

一旦jsonSerialize方法在实现 JsonSerializable 的类上实现,json_encode 将对 jsonSerialize 的返回值进行编码。

因此,您可以修改 Magento 的核心,并制作 \Tinyrocket\Magento\Objects\MagentoObjectCollection\Tinyrocket\Magento\Objects\MagentoObject 类来实现 \JsonSerializable,并将此 JsonSerialize 方法添加到他们的源代码中:

class XXX implements \JsonSerializable
{
    public function JsonSerialize()
    {
        // Returns all variables. Since we're in the object context, we've access to all of them.
        return get_object_vars($this);
    }
}

然后你通过调用 json_encode()/json_decode() 得到你的数组:

json_decode(json_encode($result), true)

虽然此解决方案可能有助于解决您的问题,但我不会推荐它,因为它需要修改 Magento 的核心,这可能会破坏其他模块并且在更新后不再工作。 您应该改为创建自己的插件并使用第一个解决方案,这是最好的方法。


两种解决方案都返回这个数组:

array (
  'collection' => 
  array (
    0 => 
    array (
      'data' => 
      array (
        'product_id' => '9',
        'sku' => 'Tilapia',
        'name' => 'Tilapia',
        'set' => '4',
        'type' => 'simple',
        'category_ids' => 
        array (
          0 => '2',
          1 => '4',
        ),
        'website_ids' => 
        array (
          0 => '1',
        ),
      ),
    ),
    1 => 
    array (
      'data' => 
      array (
        'product_id' => '10',
        'sku' => 'Deshi Rui',
        'name' => 'Deshi Rui',
        'set' => '4',
        'type' => 'simple',
        'category_ids' => 
        array (
          0 => '2',
          1 => '4',
        ),
        'website_ids' => 
        array (
          0 => '1',
        ),
      ),
    ),
    'count' => 2,
  ),
)

关于php - 将对象转换为关联数组返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30137310/

有关php - 将对象转换为关联数组返回空值的更多相关文章

  1. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  2. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  3. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  4. ruby - 多次弹出/移动 ruby​​ 数组 - 2

    我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

  5. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  6. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  7. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  8. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  9. ruby - 检查数组是否在增加 - 2

    这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife

  10. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

随机推荐