I'm really stuck trying to resolve what should be quite simple.
I Have this
<?php
$json = json_decode('{
"33540116":
{"person":
{"name":"John", "age":"36"}},
"33541502":
{"person":
{"name":"Jack", "age":"23"}}
}
');
$id = array('33540116', '33541502');
foreach($id as $id) {
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
?>
So the code is decoding a json string then using foreach to echo each result.
This json file is rather large and I'm only interested in certain records that match the id's stored in a mysql table.
To do this I have replaced the id array string above with mysql select statement.
<?php
$json = json_decode('{
"33540116":
{"person":
{"name":"John", "age":"36"}},
"33541502":
{"person":
{"name":"Jack", "age":"23"}}
}
');
$result = mysql_query("SELECT id FROM people");
$row = mysql_fetch_array($result);
$id = array($row['id']);
foreach($id as $id) {
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
?>
Although this works, it only gives me 1 result.
What I really need is to loop through the results.
Unfortunately I don't know how to construct a while loop together with foreach.
I will greatly appreciate your assistance.
UPDATE (extra question)
Thanks everyone. You have helped me solve the problem.
However, I have another question that relates to this matter.
I mentioned above that I merely wanted to echo the results.
But this isn't exactly true.
What I really want to do is update the same mysql table with the results retreived from the json file.
I have a table called people with fields id, name and age.
How can I update this table with these results?
Thanks again.
mysql_fetch_array only fetches one row at a time. You can use a while loop to continue fetching rows. The mysql_fetch_array function returns false once the whole result set has been fetched, so that will cause the while loop to terminate as desired.
Also, I removed the foreach loop on $ids. Since there will only be one element in the array it's unnecessary to put the code in a loop.
<?php
$json = json_decode('{
"33540116":
{"person":
{"name":"John", "age":"36"}},
"33541502":
{"person":
{"name":"Jack", "age":"23"}}
}
');
$result = mysql_query("SELECT id FROM people");
while ( ( $row = mysql_fetch_array($result) ) ) {
$id = $row['id'];
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
?>
Try this:
while($row = mysql_fetch_array($result)) {
$id = array($row['id']);
foreach($id as $id) {
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
}
You are using this :
$row = mysql_fetch_array($result);
This will only fetch one row from the database.
If you want to fetch more than one row, you have to call mysql_fetch_array() in a loop :
while ($row = mysql_fetch_array($result)) {
// Work with the current row
}
In your case, you'd have something like this :
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
You do not need foreach loop the while is just enough
$result = mysql_query("SELECT id FROM people");
$id = array($row['id']);
while($row = mysql_fetch_array($result))
{
echo $json->$row['id']->person->{'name'}. '<br />';
echo $json->$row['id']->person->{'age'}. '<br />';
}
You have a couple of issues. Firstly, you shouldn't be using foreach($id as $id) since you are using the same variable for both. Instead it should be foreach($ids as $id). Secondly, you can get a list of the ids and echo out the correct json values as follows
<?php
$json = json_decode('{
"33540116":
{"person":
{"name":"John", "age":"36"}},
"33541502":
{"person":
{"name":"Jack", "age":"23"}}
}
');
$result = mysql_query("SELECT id FROM people");
$ids = array();
while($row = mysql_fetch_array($result)) {
$ids[] = $row['id'];
}
foreach($ids as $id) {
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
?>
Hopefully that will solve it
Related
I'm trying to show table from json but failed, what's wrong with this:
$nip=$_POST['nip'];
$sql = "select satker,shift_description,nip FROM jamkerja
inner join master_shift on master_shift.shiftno=jamkerja.shiftno
inner join tr_jamkerjahdr on jamkerja.id_jamkerja=tr_jamkerjahdr.id_jamkerja
inner join tr_jamkerjamember on tr_jamkerjamember.trno=tr_jamkerjahdr.trno
where nip='$nip' ";
$result = $con->query($sql);
$data = array();
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
}
print $data;
And this is the table:
$json = $data;
$json_decoded = json_decode($json);
foreach($json_decoded as $data12){
echo '<tr>';
echo '<td>'.$data12[satker].'</td>';
echo '<td>'.$data12[shift_description].'</td>';
echo '<td>'.$data12[nip].'</td>';
echo '</tr>';
}
You don't need the $json_decode.Just loop through your array $data.
remove the :
$json = $data;
$json_decoded = json_decode($json);
and modify the foreach loop, adding the table tag.Also add single qoutes to your array indexes:
echo '<table>';
foreach($data as $data12){
echo '<tr>';
echo '<td>'.$data12['satker'].'</td>';
echo '<td>'.$data12['shift_description'].'</td>';
echo '<td>'.$data12['nip'].'</td>';
echo '</tr>';
}
echo '</table>';
Not sure I fully understand your question.
But let me try to help you. I think your issue is around
$json = $data;
$json_decoded = json_decode($json);
json_decode() is not needed here, the $data that you are assigning to $json is a type array. With the code you shared, I don't see any need for Json, you should directly loop through your $data.
Hope that helps.
there should be many more return values?
print_r($data);
shows that there is much more to be displayed.
Thanks for any hints,
Stefan
<?php
$data = json_decode(file_get_contents('https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-DOGE&type=sell'),TRUE);
//print_r($data);
$ncount = COUNT( $data );
for($i=0;$i<$ncount;$i++){
echo $data['result'][$i]['Quantity'] .'<br />';
}
?>
$ncount should be the count() of $data['result'];
Try this:
<?php
$data = json_decode(file_get_contents('https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-DOGE&type=sell'),TRUE);
$ncount = count($data['result']);
for($i=0;$i<$ncount;$i++){
echo $data['result'][$i]['Quantity'] .'<br />';
}
?>
While not a definite answer, you're running count on $data, but then displaying $data['result']. So if the root array only contains 3 values, you'll only go through the loop 3 times. Instead, try a foreach:
foreach ($data['result'] as $result){
echo $result['Quantity'] .'<br />';
}
You are making things WAY too difficult .. Set result to data['result'] and iterate through that
<?php
$data = json_decode(file_get_contents('https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-DOGE&type=sell'),TRUE);
$result = $data['result'];
foreach($result as $item){
echo $item['Quantity'] . '<br />';
}
?>
I have the following script which creates a multidimensional array from a MySQL query and prints the results according to categories like:
CSF (infection)GlucoseProtein (Spot Urine)Blood gasesBicarbonate (Fluid)pH (Fluid)Oxygen partial pressure (tension)(pO2)Creatinine clearanceCreatinine (Fluid)Creatinine (24 hour Urine)
$test_groups = array();
$query = "SELECT * FROM
lab_test,
model_lab_test_lookup,
lab_test_group
WHERE
lab_test.lab_test_pk = model_lab_test_lookup.lab_test_fk
AND
model_lab_test_lookup.lab_test_group_fk = lab_test_group.lab_test_group_pk
AND
model_lab_test_lookup.pathway_fk = '$pathway'
GROUP BY lab_test.lab_test_pk";
$result = mysql_query($query, $connection) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)){
$test_groups[$row['group_name']][] = $row['lab_test'];
}
foreach($test_groups as $group_name => $tests){
echo '<strong>' . $group_name . '</strong><br />';
foreach($tests as $test){
echo $test . '<br />';
}
echo '<p>';
}
Now I want to add columns in addition to $row['lab_test'] (the test name), e.g $row['lab_test_pk'] and $row['interval'] and be able to access those columns as happens in the foreach loops.
Like
$test_groups[$row['group_name']] = array(
'test_pk' => $row['lab_test_pk'],
'test_name' => $row['lab_test'],
'interval' => $row['interval']
);
What is the right way of doing this and then accessing the added columns in the last foreach loop?
$row['lab_test_pk'].','.$row['lab_test'].','.$row['interval'];
Try the above line and use . to append.
Using part solution provided by #N.M.N I have the following working:
while ($row = mysql_fetch_assoc($result)){
$test_groups[$row['group_name']][] = $row['lab_test_pk'].','.$row['lab_test'].','.$row['interval'];
}
foreach($test_groups as $group_name => $tests){
echo '<strong>' . $group_name . '</strong><br />';
foreach($tests as $test){
list($test_pk, $test_name, $test_interval) = explode(',', $test);
echo $test_pk . '<br />';
echo $test_name . '<br />';
echo $test_interval . '<br />';
}
echo '<p>';
}
I'm new to php.I'm reading a RSS feed and store in my database table.
for this I'm using
$num = count($movies->channel->item);
for ($i=0; $i<=$num-1; $i++){
$tittle= $movies->channel->item[$i]->title."<br/>";
$link=$movies->channel->item[$i]->link."<br/>";
$image=$movies->channel->item[$i]->medium_image_url."<br/>";
$des=$movies->channel->item[$i]->description."<br/>";
$city=$movies->channel->item[$i]->city;
}
how can display all data with foreach loop?
foreach($movies->channel->item as $opt){
echo $tittle= $opt->title."<br/>";
echo $link=$opt->link."<br/>";
echo $image=$opt->medium_image_url."<br/>";
echo $des=$opt->description."<br/>";
echo $city=$opt->city;
}
You can just echo out the result of your statements (I've also changed it to a foreach as requested):
foreach ($movies->channel->item as $item) {
$tittle= $item->title."<br/>";
$link=$item->link."<br/>";
$image=$item->medium_image_url."<br/>";
$des=$item->description."<br/>";
$city=$item->city;
echo $tittle.$link.$image.$des.$city;
}
This should work:
foreach ($movies as $movie)
$tittle = $movie->title."<br/>";
$link = $movies->link."<br/>";
$image = $movie->medium_image_url."<br/>";
$des = $movie->description."<br/>";
$city = $movie->city;
}
foreach ($movies->channel->item as $item) {
echo $item->title.'<br />';
echo $item->link.'<br />';
echo $item->medium_image_url.'<br />';
echo $item->description.'<br />';
echo $item->city;
}
I have echoed them because I think this is what you are wanting to do - your code reassigns variables on each iteration but does nothing with them. They are overwritten each time, so they will only hold the values from the last iteration at the end.
EDIT
You can easily modify this to insert rows into your database by doing something like this:
foreach ($movies->channel->item as $item) {
echo $item->title.'<br />';
echo $item->link.'<br />';
echo $item->medium_image_url.'<br />';
echo $item->description.'<br />';
echo $item->city.'<br />';
// Build the query - change the names of your table and columns as appropriate
$query = "INSERT INTO `tablename`
(`title`,`link`,`medium_image_url`,`description`,`city`)
VALUES
('$item->title','$item->link','$item->medium_image_url','$item->description','$item->city')";
// Do the query - do NOT show the output of mysql_error() in a production environment!
if (!mysql_query($query)) echo 'Oh no! Something went wrong with the query: '.mysql_error();
}
Alternatively, you can turn it all into one query, to minimise database traffic:
$rows = array();
foreach ($movies->channel->item as $item) {
echo $item->title.'<br />';
echo $item->link.'<br />';
echo $item->medium_image_url.'<br />';
echo $item->description.'<br />';
echo $item->city.'<br />';
// Add this entry to $rows
$rows[] = "('$item->title','$item->link','$item->medium_image_url','$item->description','$item->city')";
}
// Build the query - change the names of your table and columns as appropriate
$query = "INSERT INTO `tablename`
(`title`,`link`,`medium_image_url`,`description`,`city`)
VALUES ".implode(', ',$rows);
// Do the query - do NOT show the output of mysql_error() in a production environment!
if (!mysql_query($query)) echo 'Oh no! Something went wrong with the query: '.mysql_error();
I've got the following code that I can't seem to get working:
function drawTable($result)
{
var_dump($result);
echo '<table border = "1" cellpadding="10">';
echo '<tr>
<th>Album</th>
<th>Tracks</th>
<th>Price</th>
<th>Purchase</th>
</tr>';
foreach($result as &$album) {
$albumID = $album['Album_ID'];
var_dump($albumID);
//echo '<tr><td><img src="' . $resultRow['Image_URL'] . '" width="200px" height="200px"> </td>';
$tracksQuery = "SELECT Track_Title FROM Track WHERE (Album_ID = '$albumID')";
var_dump($tracksQuery);
$DBConnector2 = new DBConnector();
$tracks = $DBConnector2->getSQL($tracksQuery);
var_dump($tracks);
while ($trackTitle = mysqli_fetch_array($tracks)) {
echo $trackTitle['Track_Title'] . '<br />';
}
}
echo '</table>';
}
The var $result is a list of Album_IDs. I want to iterate over this using a foreach and also to run a query to get its associated tracks.
The var_dump gives:
object(mysqli_result)#4 (0) { }
In addition, the SQL I'm using for $result is
SELECT *
FROM Album
ORDER BY Album.Album_Name ASC
Very basic. You can see the other SQL use in the loop.
What am I doing wrong? Thanks.
I assume that $result is the return of a mysql_query function. You can't do that as it is still a reference to a mysql resultset, not the real mysql result.
Instead of using the foreach iteration, use a while loop like the following:
while ($album = mysql_fetch_assoc($result)) {
...
...
}
I'm not so sure whether in the first place you may pass a mysql result reference in a function but you can give it a try :)
You cannot use foreach with mysqli, that I know of. Change it to this:
while ($row = $result->fetch_assoc()) { ...