Foreach loop Json array - php

I am learning to work with Json at the moment, I have figured out how to display data for Name and Craft in space in the moment.
I cannot figure out how to display number of people.
Is not correct, I am receiving error
foreach ($json_data['number'] as $key => $value) {
echo $value;
}
Also does not work
foreach($json_data as $key=>$value)
{
echo $key['number'];
}
// Read JSON file
$json = file_get_contents('http://api.open-notify.org/astros.json');
//Decode JSON
$json_data = json_decode($json,true);
HTML
<table>
<tr>
<th>Name</th>
<th>Craft</th>
</tr>
<?php foreach($json_data['people'] as $key=>$value): ?>
<tr>
<td><?php echo $value['name']; ?></td>
<td><?php echo $value['craft']; ?></td>
</tr>
<?php endforeach; ?>
</table>
I want to display number of people in the space by using foreach loop

Change your code to
<?php
// Read JSON file
$json = file_get_contents('http://api.open-notify.org/astros.json');
//Decode JSON
$json_data = json_decode($json,true);
$peopleCount = 0;
?>
<table>
<tr>
<th>Name</th>
<th>Craft</th>
</tr>
<?php foreach($json_data['people'] as $key=>$value):
$peopleCount++;
?>
<tr>
<td><?php echo $value['name']; ?></td>
<td><?php echo $value['craft']; ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php
echo "Total People count: ". $peopleCount;
explanation:
$peopleCount variable is holding the number of people.
At first, its values is 0.
When iterating over the array the $peopleCount's value is incrementing by 1 ($peopleCount++; is equal to $peopleCount = $peopleCount +1;)
PS:
Your code had missing PHP closing tag at line number 8. I fixed it.

foreach is used to loop through an array. In your JSON output number is not returned as an array, so you do not need to use foreach loop for displaying number. You can just display the Number using following code:
<?php echo $json_data['number']; ?>

Related

Display some html if mysqli_fetch_assoc is empty while loop php [duplicate]

This question already has answers here:
Checking if mysqli_query returned any values?
(2 answers)
Closed 3 months ago.
I'm using while loop to fetch data from the database I want to display like nothing found the result is null or empty. I've tried using if/else with like: if (empty($jobs)) echo 'nothing found'; that doesn't work. if(!mysqli_fetch_assoc($jobs)) works but if don't show the jobs if available.
Loop
<?php while ($job = mysqli_fetch_assoc($jobs)) { ?>
<tr class="custom-table-body-titles">
<td><?php echo h($job['updated_at']); ?></td>
<td>
<?php echo h($job['title']); ?>
</td>
<td>0/<?php echo h($job['required_freelancers']); ?></td>
<td><?php echo h($job['delivery_time']); ?> Days</td>
<td>$<?php echo h($job['budget']); ?></td>
<td>
Apply
</td>
</tr>
<?php } ?>
You have to do a validation to check if any results were found before even starting the loop. Assuming $jobs is an instance of mysqli_result returned by mysqli_query().
if (mysqli_num_rows($jobs) > 0)
{
// your while loop
}
else
{
echo "no jobs found";
}
You should keep PHP and HTML separate as much as you can.
You can fetch all results into an array before and then foreach on that array.
$jobs = $jobs->fetch_all(MYSQLI_ASSOC);
if($jobs) {
foreach ($jobs as $job) {
}
} else {
}
A good question which is sadly most of time is answered incorrectly.
It's a very bad practice to mix the database-related code and HTML code. There should never be a while loop like this.
Instead, the data should be fetched into array,
$jobs = [];
while ($row = mysqli_fetch_assoc($result)) {
$jobs[] = $row;
}
which is then used to output the data. And once you have this array, you can use it to tell whether the query returned any data or not:
<?php if ($jobs) { ?>
<?php foreach ($jobs as $job) { ?>
<tr class="custom-table-body-titles">
<td><?php echo h($job['updated_at']); ?></td>
<td>
<?php echo h($job['title']); ?>
</td>
<td>0/<?php echo h($job['required_freelancers']); ?></td>
<td><?php echo h($job['delivery_time']); ?> Days</td>
<td>$<?php echo h($job['budget']); ?></td>
<td>
Apply
</td>
</tr>
<?php } ?>
<?php } else {?>
no data
<?php } ?>

Mysql returns duplicate in html table

I am trying to populate html table with data from mysql.But i am stuck on this part where each time i add some data it keeps repeating. On the picture below you can see that Test 1 repeat each time for every P20,P21,P24,P22,P23 and i needed to be one TEST1 for all of them. When i add Test 2 with value 19000 its making new P20 and all data come from Test 1 to Test 2. Can someone help me how to fix this.Any hint or suggestion wil be appreciated. Thank you all very much (Sorry for my bad english)
This is code that runs this
$sql = 'SELECT DISTINCT Pers.naam, Rol.funkcija,pdata.broj
FROM ids
left JOIN Pers ON ids.persid = Pers.id
left JOIN Rol ON ids.rolid = Rol.id
left JOIN pdata ON ids.pdataid = pdata.id
';
$query = $conn->prepare($sql);
$query->execute();
$testing = $query->fetchAll(PDO::FETCH_ASSOC);
?>
<table>
<tr>
<th>P Small <small>(NONE)</small></th>
<?php
foreach ($testing as $test):
?>
<th>
<?php
echo $test['naam'] . '<br />';
?>
</th>
<?php
endforeach;
?>
</tr>
<tr>
<th>TESTING LINES</th>
</tr>
<?php foreach ($testing as $test): ?>
<tr>
<td><?php echo $test['funkcija']; ?></td>
<?php endforeach; ?>
<?php
foreach ($testing as $test):
?>
<td><?php echo $test['broj']; ?></td>
<?php
endforeach;
?>
</tr>
</table>
I would like to have it like this
There is some refactoring required to get to the output you want.
You seem to be enumerating quite a lot of data from your SQL result, so there is some grouping required to make things easier.
To get the appropriate number to each "naam" and "funkcija" you can use array_filter which however could theoretically return several numbers in each case.
You'll also have to nest a couple foreach instead of running them after one another.
If I understand your data structure correctly, this should at least give you a good starting point for the output you want:
<?php
// ...
$testing = $query->fetchAll(PDO::FETCH_ASSOC);
$naams = array_unique(array_column($testing, "naam"));
$funkcijas = array_unique(array_column($testing, "funkcija"));
?>
<table>
<tr>
<th>P Small <small>(NONE)</small></th>
<?php foreach ($naams as $naam): ?>
<th>
<?php echo $naam; ?>
</th>
<?php endforeach; ?>
</tr>
<tr>
<th>TESTING LINES</th>
</tr>
<?php foreach ($funkcijas as $funkcija): ?>
<tr>
<td><?php echo $funkcija; ?></td>
<?php foreach ($naams as $naam): ?>
<?php
$data = array_filter(
$testing,
function ($v) use ($naam, $funkcija)
{
return $v["naam"] === $naam && $v["funkcija"] === $funkcija;
}
);
foreach ($data as $value): ?>
<td><?php echo $value["broj"]; ?></td>
<?php endforeach; ?>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>

For loop inside Foreach

I got a foreach which loops through my database for each user.
<?php
foreach($users as $user) {
?>
<tr>
<td>
<?php
for ($i=1; $i < 52; $i++) {
echo $i;
}
?>
</td>
<td>
<?php echo $user['firstname']; ?>
</td>
</tr>
<?php
}
?>
This loop through database and echos the username, now I tried to build a for loop inside this so that every user has a number, I took as an example a very basic for loop ( it will be changed later).
The problem is that I get all numbers printed out for each user, but I just want to print out the number once for a user. How do I solve this.
If you want unique index number for user, you do not need extra loop.
Just add an increment variable:
And increment it in existing loop.
<?php
$i=0;
foreach($users as $user) {
++$i; // For printing first user, it will be 1 not 0.
// Therefore, increment is placed before printing name.
?>
<tr>
<td><?php echo $i;?></td>
<td><?php echo $user['firstname']; ?></td>
</tr>
<?php
}
?>
This should be enough to achieve what you're trying to do :
Your for() isn't needed since foreach() already create a loop, you just have to use this loop to increment a value (here called $i) then display it.
Also you should avoid to open your php tags ten thousands times for a better visibility into your code :)
<?php
$i = 0;
foreach($users as $user) {
$i++;
echo'<tr>
<td>'.$i.'</td>
<td>'.$user['firstname'].'</td>
</tr>';
?>
<?php
$i=1;
foreach($users as $user) {
?>
<tr>
<td>
<?php
echo $i++;
?>
</td>
<td>
<?php echo $user['firstname']; ?>
</td>
</tr>
<?php
}
?>
Try to use the key in foreach
<?php foreach ($users as $key => $user) : ?>
<tr>
<td><?php echo $key; ?></td>
<td><?php echo $user['firstname']; ?></td>
</tr>
<?php endforeach; ?>

PHP table from JSON without names in array

I am having a problem with api Yandex.
I have to get data from api and make with php the table:
Source Users New Pages Bounce Goal1 Goal2
organic s1v1 s1v2 s1v3 s1v4 s1v5 s1v6
referral s2v1 s2v2 s2v3 s2v4 s2v5 s2v6
(none) s3v1 s3v2 s3v3 s3v4 s3v5 s3v6
After json_decode I have:
{"data":[
{"dimensions":[{"name":"organic"}],"metrics":[s1v1,s1v2,s1v3,s1v4,s1v5,s1v6]},
{"dimensions":[{"name":"referral"}],"metrics":[s2v1,s2v2,s2v3,s2v4,s2v5,s2v6]},
{"dimensions":[{"name":"(none)"}],"metrics":[s3v1,s3v2,s3v3,s3v4,s3v5,s3v6]},
]}
But I can't correctly parse it into a table. So far I have written code only for the first column Source, and then stuck:
<?php
$metrika_o = json_decode($metrika);
echo "<table>
<tr>
<td><strong>Source</strong></td>
<td><strong>Users</strong></td>
<td><strong>New</strong></td>
<td><strong>Pages</strong></td>
<td><strong>Bounce</strong></td>
<td><strong>Goal1</strong></td>
<td><strong>Goal2</strong></td>
</tr>";
foreach($metrika_o->data as $data)
foreach($data->dimensions as $source)
:
?>
<tr>
<td><?php echo $source->name?></td>
</tr>
<?php endforeach;
echo "</table>";
?>
The Source number is constantly changing, the set of columns is fixed.
Please help me to solve this task
You are on the right way:
<?php foreach($metrika_o->data as $data): ?>
<tr>
<td><?php echo $data->dimensions[0]->name; ?></td>
<?php foreach(explode(',',$data->metrics) as $col):
<td><?php echo $col; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>

multiply 2 values from different table using codeigniter and postgresql foreach()

Here's the code from my
Controller Page
public function table1(){
$this->load->model('test_model');
$data['value']= $this->test_model->getAlltable1();
$data['value2']= $this->test_model->getAlltable0();
$this->load->view('table1', $data);
}
Views Page
<table class="table">
<tbody>
<?php foreach ($value as $v){ ?>
<?php foreach ($value2 as $v2){ ?> //different table
<tr>
<td><?php echo $v->tech_voc?></td>
<td><?php echo ($v->tech_voc*$v2->tech_voc)?></td>
</tr>
<?php } ?>
<?php } ?>
The output is somewhat like this
1 .75
1 .75
1 .75
1 .75
What I want to display is something like this
1 .75
What happen here is that, instead it multiply once, it all multiply each row. And I think it is because I put foreach inside a foreach Please help me.
EDIT
Oh yeah, I already tried deleting the foreach value2
but it says v2 is undefined variable
HOPE it helps.
NEW EDIT:---------------------------------------
If you're trying to multiply where the keys are the same ($value[0]*$value2[0], $value[1]*$value2[1], etc) try this.
<?php
$col1_sum = 0;
$col2_sum = 0;
foreach ($value as $k => $v){ ?>
<tr>
<td><?php echo $v->tech_voc?></td>
<td><?php echo ($v->tech_voc*$value2[$k]->tech_voc)?></td>
<?php //update sums
$col1_sum += $v->tech_voc;
$col2_sum += ($v->tech_voc*$value2[$k]->tech_voc);
?>
</tr>
<?php } ?>
<!-- row with sums -->
<tr>
<td><?php echo $col1_sum?></td>
<td><?php echo $col2_sum?></td>
</tr>
Edited based on comments/chat to include a sum row.

Categories