将对象重写为数组?

时间:2012-04-08 13:12:58

标签: php arrays object

我正在使用curl从网站上获取一些数据。在我处理之后,我设法让它达到这个状态:

Array ( 
[GraphicRiver] => Array ( [0] => stdClass Object 
    ( 
        [id] => 698515 
        [item] => Alien Icons Set 
        [url] => http://graphicriver.net/item/alien-icons-set/698515 
        [user] => chaoscod3r 
        [thumbnail] => http://2.s3.envato.com/files/23574322/Thumb.jpg 
        [sales] => 5 
        [rating] => 0 
        [cost] => 5.00 
        [uploaded_on] => Mon Oct 24 17:16:20 +1100 2011 
        [tags] => alien icons, clean icons, easy editing, icons pack, minimalist icons pack, resizable, simple icons, vector icons, vector shapes 
        [category] => icons/miscellaneous 
        [live_preview_url] => http://3.s3.envato.com/files/23574321/Preview.jpg 
    )
)

)

但是我想要的而不是那个stdClass对象是Array,那么如何重写这种数组来制作那个对象和数组?

这是我用来获取上述内容的方法:

public function all_items_by_site($user_name) {

  $items_by_marketplace = $this->user_items_by_site($user_name);

  $marketplaces = array();

  $items = array();

  foreach ($items_by_marketplace as $key) {
     $marketplaces[] = array(
        'Marketplace'  => $key->site,
        'Items'        => $key->items
     );
  }

  foreach ($marketplaces as $key) {
     $items[$key['Marketplace']] = $this->new_files_from_user($user_name, $key['Marketplace']);
  }

  return $items;

}

我正在使用这个api包装器作为我想要开发的基础api包装器:https://github.com/JeffreyWay/Envato-Marketplace-API-Wrapper-in-PHP

2 个答案:

答案 0 :(得分:6)

您可以轻松地将stdClass个对象转换为数组:

$array = (array)$object;

在你的具体案例中:

foreach ($array['GraphicRiver'] as &$item) {
    $item = (array)$item;
}
unset($item);

答案 1 :(得分:1)

最简单的方法(虽然这不是真正的语义方式)是使用json_encodejson_decode的组合:

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

这很容易,但我不推荐大阵列 另一种方法是遍历您的数组并使用(array)

应用类型转换
$array = array_map(function($el) {
    return (array)$el;
}, $orig);