Form Table out of JSON Array - php

I've got a simple question.
I'm getting a PHP Array from a mysql query and I encoded it so it looks like this:
[
{
"ID": "111111",
"JoinDate": "2015-05-13",
"Nickname": "TestUser1"
},
{
"ID": "222222",
"JoinDate": "2015-05-06",
"Nickname": "TestUser2"
},
{
"ID": "333333",
"JoinDate": "2000-01-01",
"Nickname": "TestUser3"
}
]
How can I iterate through this Array and Form a simple HTML Table?

Heres an example of outputting array elements in table rows.
foreach ($elements as $element) {
echo '<tr><td>'. $element['ID'].'</td><td>>'. $element['Nickname'].'</td></tr>';
}

Related

how to access the name or url content from this array in php?

How can I show this data inside an HTML table in PHP?
I convert the JSON to an array using the "json_decode" function.
Just wanted to know a method to convert the array to an HTML table or fetch specific details such as name or URL.
Thanks
[
{
"trends": [
{
"name": "#GiftAGamer",
"url": "http://twitter.com/search?q=%23GiftAGamer",
"promoted_content": null,
"query": "%23GiftAGamer",
"tweet_volume": null
},
{
"name": "#TransDayOfRemembrance",
"url": "http://twitter.com/search?q=%23TransDayOfRemembrance",
"promoted_content": null,
"query": "%23TransDayOfRemembrance",
"tweet_volume": 45852
},
{
"name": "MourĂ£o",
"url": "http://twitter.com/search?q=Mour%C3%A3o",
"promoted_content": null,
"query": "Mour%C3%A3o",
"tweet_volume": 12614
},
{
"name": "Taysom Hill",
"url": "http://twitter.com/search?q=%22Taysom+Hill%22",
"promoted_content": null,
"query": "%22Taysom+Hill%22",
"tweet_volume": 20311
},
{
"name": "Geraldo",
"url": "http://twitter.com/search?q=Geraldo",
"promoted_content": null,
"query": "Geraldo",
"tweet_volume": 30166
}
],
"as_of": "2020-11-20T19:37:52Z",
"created_at": "2020-11-19T14:15:43Z",
"locations": [
{
"name": "Worldwide",
"woeid": 1
}
]
}
]
First you want to understand the structure. The JSON you pasted is an array with exactly one (1) element, which is an object with the keys trends, as_of, created_at and locations.
In PHP you can access an element in an array via the index (starting at 0) $array[index], eg. $array[0].
An object on the other hand is accessible via the method syntax, which in PHP in a single arrow ->, eg. $object->attribute.
So, in order to get the name of the first element in "trends", you have to access each array and/or object from the start.
<?php
$json = json_decode($string); // json string you posted
$object = $json[0]; // get the first element of the overall array
$trends = $object->trends; // get the trends attribute of the first object, which is an array again
$first_trend = $trends[0]; // array can be accessed via the index again.
$first_name = $first_trend->name; // a trend is an object again with attributes name, url, promoted_content, etc.
Of course you want to access this data in an dynamic way, which is where loops come in handy. PHP offers foreach, which can iterate over array elements and also object attributes. Take a read: https://www.php.net/manual/en/language.oop5.iterations.php
https://www.php.net/manual/en/control-structures.foreach.php
With this, you can iterate all trends like this
foreach($trends as $trend) {
echo $trend->name;
}
You of course can wrap HTML (eg. a table) around.
<?php
echo "<table>";
$json = json_decode($string);
$trends = $json[0]->trends;
foreach($trends as $trend) {
echo "<tr>"; // new table row
foreach($trend as $key => $value) {
// this iterates over all attributes of trend
echo "<td>" . $value . "</td>";
}
echo "</tr>"; // close table row
}
echo "</table>";
?>
This is an example of a loop inside another loop. The outer loop iterates all trends, the inner loop iterates the attributes of the current trend.

How to get a specific value from a json array out of a list of arrays

everyone, I was just trying to find out a way to get the value of a link from a JSON array , after I have searched the array with help of Id. I am using PHP's file_get_contents and the webpage from which information is to be taken looks like
[{
"id":"2972",
"name": "AbC",
"link":"any link",
"epg": "any link",
"dur": "disabled",
"language": "y",
"category": "TOP 100",
"logo": "any url here"
},
{
"id": "1858",
"name": "Efg",
"link": "url",
"epg": "url",
"dvr": "disabled",
"language": "E",
"category": "TOP 100",
"logo": "url"
}]
From here suppose I have been given an Id 1858 so I have to find a link from the array of Id having 1858
I am a beginner in PHP and was just fidgeting around with a piece of code and tried to get its solution and a big Thanks To You For Your Answer and valuable Time.
if you are using file_get_contents('php://input'); then you should try this to access json data
$json = file_get_contents('php://input'); //get json data in variable
$array = json_decode($json); //parse json data in php array
// assecc the array with use of foreach loop
foreach($array as $obj){
//access the json element here like $id = $obj->id; $url = $obj->link;
//if you want to check the id value in array you can compare value with if condition
$id = $obj->id;
// find link for specific id
if($id =='1858'){
$url = $obj->link;
echo $url; // do something with link
//you can use break; statement if you found your element and terminate the loop
}
}
You can use array_column, to map pairs of json keys/values:
<?php
$json ='
[
{
"id": 3,
"link": "http:\/\/example.com\/3"
},
{
"id": 5,
"link": "http:\/\/example.com\/5"
}
]';
$data = json_decode($json, true);
if($data !== null) {
echo array_column($data, 'link', 'id')[5] ?? null;
}
Output:
http://example.com/5
To understand this we can see the result of array_column.
var_export(array_column($data, 'link', 'id'));
Output:
array (
3 => 'http://example.com/3',
5 => 'http://example.com/5',
)
So with the above code, we are checking for and outputting the associated index of 5 (the original id).

How to write SELECT query in mysql json Array data

I am trying to get the email from the array json, but it returns null value
[
{
"name": "Arun",
"email": "arun#arun.com"
},
{
"name": "Arun kumar",
"email": "arunkumar#gmail.com"
}
]
and my Json query is select json->>"$.name" as email from json
But this query is return null value
I tested the following and worked for me on your json sample
$json='[{"name": "Arun", "email": "arun#arun.com"}, {"name": "Arun kumar", "email": "arunkumar#gmail.com"}]';
$data=json_decode($json,true);
foreach ($data as $key => $value) {
echo $value["email"] . "<br>";
}
This should work,
JSON_EXTRACT(yourstring, '$[*].email')
yourstring - your json data or field in database
$ is json syntax to search json object
* means all multidimensional array
email check email in * values

How to fetch PHP database values in Json?

I have to create Matrix tree view in my project. So am plan to use json. My question is how to fetch PHP values in Json ?. I did static matrix tree but i want dynamic. Thank you for advance.
My code is following:
<?php
include('db.php');
$select = mysql_query("select * from table1");
while($row = mysql_fetch_array($select))
{
?>
{
"name": "A", // Here database values come $row['name'];
"children": [
{
"name": "B",
"children": [
{"name": "B-1"}
]
},
{
"name": "C",
"children": [
{"name": "C-1", "size": 1082},
{"name": "C-2", "size": 1681}
]
},
{
"name": "D",
"children": [
{
"name": "D-1",
"children": [
{"name": "D-1 1", "size": 1302},
{"name": "D-1 2", "size": 6703}
]
},
{"name": "D-2", "size": 16540}
]
}
]
}
<?php
}
?>
In this example Im using the mysqli driver. Do not use the mysql driver.
you just need to convert your output data into a json object.
Its possible to extract all the rows at once which is going to give you a marginally less overhead.
$data = mysqli_fetch_all($select); // returns everything in an associative array
$json_data = json_encode($data); // converts that array to json.
if you need specific keys, then manipulate your query to rename columns as necessary eg.
$query = "select name as firstname from ....";
You can just retrieve data from your database and store it in arrays like you normally would. Then call PHP's built in function json_encode() to transform your PHP array into json (assuming your PHP array is well formed (which should be the case if you get it out of a database)).
You could argue that this is slower because you're iterating over the data twice instead of once, but it shouldn't matter, the complexity remains the same.

PHP json decode from database

I have this json encode in the database, and i want just echo values name_r in foreach , how is it?
[{
"name_r": "saeed",
"units": ["salam", "11", "11", "khobe", "22", "22", "salam"],
"price_change": ["33", "33", "33", "44", "44", "44"]
}, {
"name_r": "salavat",
"units": ["55", "55", "khobe", "66", "66"],
"price_change": ["77", "77", "77", "88", "88", "88", "99", "99", "99"]
}]
this my php, that have error(Message: Undefined index: name_r - Line Number: 179):
$query = $this->db->query("SELECT * FROM table ORDER BY id desc");
$data = array();
foreach ($query->result() as $row)
{
$data[] = json_decode($row->residence,true);
echo $data["name_r"].'<br>'; //Line Number: 179
}
Assuming that the json_encoded data you provided is stored in one row of the database, the json_decode will give you an array of arrays. To echo all the name_r fields, you would need to:
foreach ($query->result() as $row){
$data = json_decode($row->residence,true);
foreach($data as $datum){
echo $datum['name_r'];
}
}
You used [] in your assignment. This means that the result of the json_decode will be pushed at the end of your array.
Using var_dump($data) should help you understand what your array actually looks like, and solve your problem by yourself.
Assuming the example JSON you showed is data from a single record. The data is an array of objects, so you'll need an inner loops that loops over the array from each returned record.
foreach ($row->residence as &$value) {
$data = json_decode($value,true);
echo $data["name_r"].'<br>';
}
I am not a PHP dev, so I am unsure if my syntax is right. But hopefully you get the idea.

Categories