Thursday, 30 August 2018

PHP - Convert an associative array to an array

I am trying to convert an Associative Array in the form of an HTML Table. This is how the Array looks like

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

And this is the code which I have written in PHP for converting the array to a table
<?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();
$data = $result->get( "data" );
echo "<table border='1'>
    <tr><td>Project Name</td>
    <td>Hourly Rate</td>
    </tr>";
        foreach($data as $key=>$fruit) {
                        ?>
                     <tr><td><?php echo $fruit["Name"];?></td>
                     <td><?php echo $fruit["hourly-rate"];?></td></tr>
        <?php ;}
    echo "</table>";
?>

I would like to display a table with 2 columns- Project Name and Hourly Rate
But once I execute the code it throws an error Fatal error: Cannot use object of type Harvest_Project as array on line 24. It is referring to this line
<tr><td><?php echo $fruit["Name"];?></td>

Kindly suggest how to go about it.

You can't access objects and arrays the same way. Use the -> operator instead:
 <tr><td><?php echo $fruit->name;?></td>
 <td><?php echo $fruit->{'hourly-rate'};?></td></tr>

You will need to use the braces around hourly-rate because variables can't have dashes in the name. They're treated as subtraction operators instead.

0 comments:

Post a Comment