user3402248
user3402248

Reputation: 469

Printing an Associative Array from an Array Object in PHP?

I have an Array Object which I would like to print as an Associative Array

<?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(); ?>

It should print something like this.

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

How can I achieve this?

Update

I tried doing a varexport. But it gives something like this

 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

This is not what I am looking for. The object should clearly list the fields it has.

Upvotes: 1

Views: 78

Answers (1)

BVengerov
BVengerov

Reputation: 3007

If there's a need to get visibility types as well in the string representation of the object's properties, it can be solved quite simply with 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);

The output looks like this:

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

Warning getProperties might not get inherited properties depending on the PHP version; in this case see examples of how to recursively get them all here.

Upvotes: 1

Related Questions