This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Displaying distinct columns and non-distinct column in one table
I have 3 tables. One is userinfo (which where you can find Name), then logs for login details and evaluation for user evaluation of the activity. They are connected by the field attendee_id.
When I joined them it gives me this output:
What I want is to have an output like this:
When I use GROUP BY Name it returned only one row for each and not returning other data.
It can be done like this. In this example I have hard coded the $rows array, but you can replace that with your array of rows from the database.
<?php
$rows = array(
array(
'name' => 'Juan',
'login' => '09:00:01',
'evaluation' => 'Yes'
),
array(
'name' => 'Juan',
'login' => '09:00:02',
'evaluation' => 'Yes'
),
array(
'name' => 'Juan',
'login' => '09:00:03',
'evaluation' => 'Yes'
),
array(
'name' => 'Jose',
'login' => '09:00:04',
'evaluation' => 'No'
),
array(
'name' => 'Jose',
'login' => '09:00:05',
'evaluation' => 'No'
)
);
?>
<table>
<tr>
<th>Name</th>
<th>Login</th>
<th>Evaluation</th>
</tr>
<?php
$prevName = '';
foreach($rows as $row):
if($prevName == $row['name']) {
$name = '';
} else {
$name = $prevName = $row['name'];
}
?>
<tr>
<td><?php echo htmlspecialchars($name); ?></td>
<td><?php echo htmlspecialchars($row['login']); ?></td>
<td><?php echo htmlspecialchars($row['evaluation']); ?></td>
</tr>
<?php endforeach; ?>
</table>
The result is:
I tried doing this a few times and gave up. In the end, I formatted the output in PHP by checking if the value for 'name' in the current row is different to the previous one:
<?php
//Assume the query has been done
//...
$lastName='';
echo '<table>';
while ($row=mysql_fetch_assoc($query_result))
{
if ($row['name']!=$lastName)
{
$lastName=$row['name'];
} else
{
$row['name']='';
}
echo '<td>'.implode('</td><td>',$row).'</td>;
echo '<tr>';
}
echo '</table>';
It's not pretty but it'll get you the result you want. You can tart it up by
Related
I have an array like this:-
$str = array(
array(
'amount' => 1.87,
'user' => 'hello',
),
array(
'amount' => 0.9,
'user' => 'test',
),
array(
'amount' => 9,
'user' => 'hello',
),
array(
'amount' => 1.4,
'user' => 'test',
)
);
Now I show this data in HTML table like this for user 'test' :-
<thead>
<tr>
<th>Amount</th>
<th>User</th>
</thead>
<tbody>
<tr>
<td><?php
foreach ($str as $new_str) {
if ($new_str['user'] == "test") {
echo $new_str['amount'];
echo "<br />";
}
}
?></td><td><?php
foreach ($str as $new_str) {
if ($new_str['user'] == "test") {
echo $new_str['user'];
echo "<br />";
}
}
?></td>
</tr>
</tbody>
But now the problem is that when I use this code it shows the amount and user as a whole instead of two different rows. How can I fix this? Any help?
You just need to move your foreach loop outside of the <tr>...</tr> structure. This should work:
<?php foreach($str as $new_str){
if($new_str['user']=="test"){
echo "<tr><td>" . $new_str['amount'] . "</td><td>" . $new_str['user'] . "</td></tr>";
}
}
?>
Output (for your data)
<tr><td>0.9</td><td>test</td></tr>
<tr><td>1.4</td><td>test</td></tr>
Your tr was not repeating. output image I hope this will help.
<?php
$str = array(
array(
'amount' => 1.87,
'user' => 'hello',
),
array(
'amount' => 0.9,
'user' => 'test' ,
),
array(
'amount' => 9,
'user' => 'hello',
),
array(
'amount' => 1.4,
'user' => 'test',
)
);
?>
<table>
<thead>
<tr>
<th>Amount</th>
<th>User</th>
</tr>
</thead>
<tbody>
<?php foreach($str as $new_str) {
if($new_str['user'] == "test"){
echo '<tr>';
echo '<td>'.$new_str['amount'].'</td>';
echo '<td>'.$new_str['user'].'</td>';
echo '</tr>';
}
} ?>
</tbody>
</table>
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.
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>
Since you are trying to get a single project using api, Use the below code
$project_id='10122036';
$result=$api->getProject($project_id);
if( $result->isSuccess() ) {
$project = $result->data;
echo $project->get( "name" );
echo $project->hourly-rate;
}else{
echo "No data from API";
}
If you see the out put "No data from API", then there is not data returned from API
I have multiple files that have this name format field1_field2_field3.pdf. I separated each field and I want to return it to the view and paginate it. Can it be done? So far I have managed to explode the filename but only one file is returned to the view. Please help.
Controller :
$this->load->helper('directory');
$map = directory_map('./assets/data/');
$nric = $this->session->userdata('nric');
foreach($map as $row)
{
$separate = explode('_',$row);
}
$data['name'] = $separate[0];
$data['product'] = $separate[1];
$data['policyno'] = substr($separate[2],0,strlen($separate[2])-4);
$this->load->view('includes/user/header');
$this->load->view('user/statements',$data);
$this->load->view('includes/user/footer');
View
<tr>
<td><?php echo $name; ?></td>
<td><?php echo $product; ?></td>
<td><?php echo $policyno; ?></td>
</tr>
In your Controller you want the data array to contain multiple value so do something like this
EDIT: I am assuming that your $map variable is something like this (do a print_r if you want to see)
$map = [
'field1_field2_field3.pdf',
'field11_field22_field33.pdf',
'field111_field222_field333.pdf'
]
So using the loop
foreach($map as $row)
{
$separate = explode('_',$row);
$data[] = [
'name' => $separate[0],
'product' => $separate[1],
'policyno' => substr($separate[2],0,strlen($separate[2])-4)
];
}
Now doing as mentioned above in the foreach loop will give you $data like
$data = [
0 => [
'name' => 'field1',
'product' => 'field2',
'policyno' => 'field3',
],
1 => [
'name' => 'field11',
'product' => 'field22',
'policyno' => 'field33',
],
2 => [
'name' => 'field111',
'product' => 'field222',
'policyno' => 'field333',
],
]
this $data you can pass to your view, as you were doing
$this->load->view('user/statements',$data);
then in your view you can have something like
<table>
<?php foreach ($data as $dataRow):?>
<tr>
<td><?php echo $dataRow['name']?></td>
<td><?php echo $dataRow['product']?></td>
<td><?php echo $dataRow['policyno']?></td>
</tr>
<?php endforeach?>
</table>
I think this should work :)
Now use some fancy JavaScript plug-in and create a paginated view
I am attempting to print out a table of the PHP multi-dimensional associative arrays. There are arrays for the class, assignments, students, scores.
I am familiar with MySQL queries, but I am not sure how to print out the table from a PHP multi-dimensional associative arrays. My thought process to access the score for the students' assignments for the class is similar to MySQL, but I know that doesn't work here. For a one dimensional, seems simple enough, but a multi-dimensional nested associative arrays I am not sure how to approach this?
Thanks in advance!
<?php
ini_set('display_errors', 'on');
$class=array (
'cat' =>
array (
2 =>
array (
'num' => '3',
'name' => 'Homework',
),
),
'assignments' =>
4 =>
array (
'clid' => '5000001001388',
'assnid' => '1',
'cat' => '3',
'due' => '20100802',
'points' => '5',
'title' => 'American Revolution',
),
),
'students' =>
array (
3 =>
array (
'stuid' => '460798', // stuid is the student's unique alphanumberic ID string
'num' => '4',
'first' => 'Thomas',
'last' => 'Jefferson',
'grade' => 'A', // these are summary statistics for the student for the class
'percent' => '94.7', // these are summary statistics for the student for the class
),
),
'scores' =>
array (
0 =>
array (
'assnid' => '1', // corresponds to assignment's 'assnid'
'stuid' => '460798', // corresponds to student's 'stuid'
'score' => '0', // this is the student's score
),
),
);
// display class properties
print($class["clid"]."<br>");
// display all class properties
foreach ($class["clid"] == $class["assignments"].["clid"] == $class["students"].["assnid"] as $property=>$value) {
print($property . " is " . $value . "<br>");
}
?>
So I used foreach to loop through students, assignments, and scores. I don't know if there's a better way of doing it.
echo <<<END
<body>
<table>
<thead>
<tr><th colspan="5" id="title">US History 2012</th></tr>
<tr>
<th>Students</th>
<th>ID</th>
<th>Grade</th>
<th>Percentage</th>
<th>American Revolution</th>
</tr>
</thead>
<tbody>
END;
foreach ($class["students"] as $students){
echo '<tr class="items">';
echo '<td>'.$students["first"].' '.$students["last"].'</td>';
echo '<td>'.$students["stuid"].'</td>';
echo '<td class="grade">'.$students["grade"].'</td>';
echo '<td class="perc">'.$students["percent"].'%</td>';
$i = 0;
$score4Avg = 0;
foreach ($class["assignments"] as $assignments){
foreach ($class["scores"] as $scores){
if ($scores["stuid"] == $students["stuid"] &&
$scores["assnid"] == $assignments["assnid"]){
echo '<td><input type="text" class="score'.$i.'" value="'.$scores["score"].'" onblur="recalculate();" tabindex="-1"></td>';
$i++;
}
if ($scores["assnid"] == $assignments["assnid"] &&
$assignments["title"] == "American Revolution"){
$score4Avg += $scores["score"];
}
}
}
echo '</tr>';
}
This code works well in terms of adding new entry with this dropdown category. My problem is, this sets Option1 as the default value to make sure the dropdown is not left unanswered. My question is, how do I echo the previously saved value for dropdown category? I should have it correctly displayed so I can do edit function correctly.
<tr>
<span style="font-size: 10pt" class="label label-info">Category</span><br/>
<? $options = array
(
'1' => 'Option1',
'2' => 'Option2',
'3' => 'Option3',
'4' => 'Option4',
); ?>
<?php echo form_dropdown('category_id', $options, 'Option1');?>
</tr>
I am looking forward to any help.
Have a nice day! :)
EDIT: this works (by the way there are good classes to handle forms with codeigniter out there, where you don't have to use all this code for each field and that manage validation rules etc. in a much more flexible way - keeping the view and controller very simple and moving most of it into models).
<?php $model = array(
array('value' => '1', 'display' => 'Option1'),
array('value' => '2', 'display' => 'Option2'),
array('value' => '3', 'display' => 'Option3'));
echo '<select name="category_id">';
foreach($model as $i) echo '<option '.($this->input->post('category_id') === $i['value'] ? 'selected="selected"' : '').' value="'.$i['value'].'">'.$i['display'].'</option>';
echo '</select>';
?>
in ref from your question : Edit form echoes previously saved data correctly but does not update the form fields
<?php
foreach($model as $row)
{
if($row="" )
{
$selected_category_id = '';
$options = array
(
'1' => 'Option1',
'2' => 'Option2',
'3' => 'Option3',
'4' => 'Option4',
); ?>
<?php echo form_dropdown('category_id', $options, $selected_category_id);?>
}
else
{
$selected_category_id = '$row->(database column name where vale is stored)';
$options = array
(
'1' => 'Option1',
'2' => 'Option2',
'3' => 'Option3',
'4' => 'Option4',
); ?>
<?php echo form_dropdown('category_id', $options, $selected_category_id);?>
}
}