dongxing8766 2011-09-16 16:21
浏览 65
已采纳

将对象转换为数组

I am working with WordPress and since I don't believe it is possible to sort object details, I was wondering how to go about converting my Object to an Array, so that sorting can be possible.

Any help or guidance would be greatly appreciated.

I am using the WP function get_categories();

The complete content of $category is:

$category->term_id
$category->name
$category->slug
$category->term_group
$category->term_taxonomy_id
$category->taxonomy
$category->description
$category->parent
$category->count
$category->cat_ID
$category->category_count
$category->category_description
$category->cat_name
$category->category_nicename
$category->category_parent
  • 写回答

7条回答 默认 最新

  • douren7179 2011-09-16 16:25
    关注

    If the object is not too complex (in terms of nesting) you can cast the class to an array:

    $example = new StdClass();
    $example->foo = 'bar';
    
    var_dump((array) $example);
    

    outputs:

    array(1) { ["foo"]=> string(3) "bar" } 
    

    However this will only convert the base level. If you have nested objects such as

    $example = new StdClass();
    $example->foo = 'bar';
    $example->bar = new StdClass();
    $example->bar->blah = 'some value';
    
    var_dump((array) $example);
    

    Then only the base object will be cast to an array.

    array(2) { 
      ["foo"]=> string(3) "bar" 
      ["bar"]=> object(stdClass)#2 (1) { 
        ["blah"]=> string(10) "some value" 
      }
    } 
    

    In order to go deeper, you would have to use recursion. There is a good example of an object to array conversion here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型