user3402248 user3402248 - 2 months ago 13
PHP Question

PHP For Each Loop-Not Generating Entries

I am trying to Iterate over an Associative Array which has the following structure

Output from var_export($data)

<?php
Harvest_Project::__set_state(array(
'_root' => 'project',
'_tasks' => array() ,
'_convert' => true,
'_values' => array(
'id' => '10122036',
'client-id' => '4861417',
'name' => 'ABC',
'code' => '',
'active' => 'true',
'billable' => 'true',
'bill-by' => 'Project',
'hourly-rate' => '145.0',
'budget' => '70.0',
'budget-by' => 'project',
'notify-when-over-budget' => 'true',
'over-budget-notification-percentage' => '80.0',
'over-budget-notified-at' => '2016-09-24',
'show-budget-to-all' => 'false',
'created-at' => '2016-03-15T21:38:40Z',
'updated-at' => '2016-05-31T23:19:58Z',
'starts-on' => '',
'ends-on' => '',
'estimate' => '70.0',
'estimate-by' => 'project',
'hint-earliest-record-at' => '2016-03-16',
'hint-latest-record-at' => '2016-08-11',
'notes' => '',
'cost-budget' => '',
'cost-budget-include-expenses' => 'false',
) ,
))


This is the code which I wrote to Iterate over the Array

<?php
$project_id=10122036;
$result=$api->getProject($project_id);
$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>";
?>


This code only creates the columns and for some reason does not generate the entries for each row in the table. Hence the resulting table is an Empty table.
Kindly suggest where I am going wrong.

Update

This code is for querying Harvest using the Harvest API. This is the PHP Wrapper Library http://mdbitz.com/docs/harvest-api/ which contains relevant classes and methods. getProject($project id) is a method to retrieve project details based on the project ID.

Answer

Added html table code.

$project_id='10122036';
$result=$api->getProject($project_id);
echo "<table border='1'>
    <tr><th>Project Name</th>
    <th>Hourly Rate</th></tr>";

if( $result->isSuccess() ) {
    $project = $result->data;?>

<tr><td><?php echo $project->get( "name" );?></td>
                     <td><?php echo $project->hourly-rate;?></td></tr>

<?php }else{?>
   <tr><td colspan="2">No data from API</td></tr>
<?php } ?>
</table>
Comments