繁体   English   中英

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

[英]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]=>-

我怎样才能做到这一点?

更新

我尝试做一个 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

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

如果需要在对象属性的字符串表示中也获得可见性类型,可以使用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 版本获取继承的属性; 在这种情况下,请参阅有关如何在此处递归获取它们的示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM