从数组对象中打印一个关联数组


Printing an Associative Array from an Array Object in PHP?

我有一个数组对象,我想把它打印成一个关联数组

<?php
require_once(dirname(__FILE__) . '/HarvestAPI.php');
/* Register Auto Loader */
spl_autoload_register(array('HarvestAPI', 'autoload'));
$api = new HarvestAPI();
$api->setUser( $user );
$api->setPassword( $password );
$api->setAccount( $account );
$api->setRetryMode( HarvestAPI::RETRY );
$api->setSSL(true);
$result = $api->getProjects(); ?>

它应该输出如下内容:

 Array ( [] => Harvest_Project Object ( 
               [_root:protected] => project 
               [_tasks:protected] => Array ( ) 
               [_convert:protected] => 1 
               [_values:protected] => Array ( 
                     [id] => ' 
                     [client-id] => - 
                     [name] => Internal 
                     [code] => 
                     [active] => false 
                     [billable] => true 
                     [bill-by] => none 
                     [hourly-rate]=>-

我怎样才能做到这一点?

我试着做一个vareexport。但是它给出了这样的内容

 Harvest_Result::__set_state(array( '_code' => 200, '_data' => array ( 5443367 => Harvest_Project::__set_state(array( '_root' => 'project', '_tasks' => array ( ), '_convert' => true, '_values' => array ( 'id' => '564367', 'client-id' => '2427552', 'name' => 'Internal', 'code' => '', 'active' => 'false', 'billable' => 'tr

这不是我要找的。对象应该清楚地列出它拥有的字段。

如果需要在对象属性的字符串表示中获得可见性类型,可以使用ReflectionClass:

很简单地解决这个问题。
$arrayObj = new Harvest_Project();
$reflection = new 'ReflectionClass($arrayObj);
$objStr = '';
$properties = $reflection ->getProperties();
foreach ($properties as $property)
{
    if ($property->isPublic()) $propType = 'public';
    elseif ($property->isPrivate()) $propType = 'private';
    elseif ($property->isProtected()) $propType = 'protected';
    else $propType = 'static';
    $property->setAccessible(true);
    $objStr .= "'n[{$property->getName()} : $propType] => " . var_export($property->getValue($arrayObj), true) .';';
}
var_dump($objStr);

输出如下所示:

[_foobar : private] => 42;
[_values: protected] => array (
  0 => 'foo',
  1 =>
  array (
    0 => 'bar',
    1 => 'baz',
  ),
);

警告 getProperties可能无法继承属性取决于PHP版本;在这种情况下,请参阅如何递归地获得它们的示例。