在PHP中从数组对象打印关联数组?

时间:2016-09-27 15:40:55

标签: php associative-array arrayobject

我有一个数组对象,我想打印为关联数组

<?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]=>-

我怎样才能做到这一点?

更新

我尝试过做一个varexport。但它给出了类似的东西

 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

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

1 个答案:

答案 0 :(得分:1)

如果需要在对象属性的字符串表示中获取可见性类型,则可以使用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版本;在这种情况下,请参阅如何以递归方式获取所有here的示例。

相关问题