I have a foreach loop that fetches values from mysql table. After fetching the values, their placed inside an array and then finally converted into a json object. The format of the json object has to be specific in order to work properly with third party api that I am currently using. The results I am getting currently placed all the values inside a json object. My goal is to pair values on separate json objects {},{},etc. In addition, How can I add labels inside the object for the values that were fetch?
$level_query = $db_con->prepare("SELECT a.type, COUNT(1) AS cnt
FROM academy a
GROUP BY a.type");
$level_query->execute();
$data = $level_query->fetchAll();
$level_data = array();
foreach ($data as $row) {
$type = $row["type"];
$level_data[$type] = $row["cnt"];
} // foreach ($data as $row) {
echo json_encode($level_data);
Current Format:
{" Expert":"12","Intermediate":"512","Beginner":”1002”}
Correct/Desired format Format:
{ level: "Expert", count: 12 },
{ level: "Intermediate", count: 512 },
{ level: "Beginner", count: 1002 }
Try this:
$output = array();
foreach ($data as $row) {
array_push($output, array('level'=>$row["type"], 'count'=>$row["cnt"]));
}
echo json_encode($output);
The desired format looks like a array of objects, each of which contains a level and a count property.
Data like this:
$data = array(
array('type'=>'a','cnt'=>1),
array('type'=>'b','cnt'=>2),
array('type'=>'c','cnt'=>3),
array('type'=>'d','cnt'=>4),
array('type'=>'e','cnt'=>5)
);
Comes out like this:
[{"level":"a","count":1},{"level":"b","count":2},{"level":"c","count":3},{"level":"d","count":4},{"level":"e","count":5}]
Related
Here's my Query
$rows = $mydb->get_results("SELECT title, description
FROM site_info
WHERE site_id='$id';");
I get something like:
Title1 Desc1
Title2 Desc2
etc.
I want to put that data in array so I do:
$data = array();
foreach ($rows as $obj) {
$data['title'] = $obj->title;
$data['description'] = $obj->description;
}
When I do:
print_r($data);
I only get title and description of first item... Please help :/ I checked and my query returns all what i want to be in array not only the first row.
You are over-writing array indexes each time in iteration.You need to create new indexes each time when you are assigning the values to array.
So either do:-
$data = array();
foreach ($rows as $key=>$obj) { // either use coming rows index
$data[$key]['title'] = $obj->title;
$data[$key]['description'] = $obj->description;
}
Or
$data = array();
$i=0; //create your own counter for indexing
foreach ($rows as $key=>$obj) {
$data[$i]['title'] = $obj->title;
$data[$i]['description'] = $obj->description;
$i++;// increase the counter each time after assignment to create new index
}
For display again use foreach()
foreach ($data as $dat) {
echo $dat['title'];
echo $dat['description'];
}
If the eventual goal is simply to display these values, then you shouldn't bother with re-storing the data as a new multi-dimensional array.
$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id='$id';");
If $id is user-supplied data or from an otherwise untrusted source, you should implement some form of sanitizing/checking as a matter of security. At a minimum, if the $id is expected to be an integer, cast it as an integer (an integer doesn't need to be quote-wrapped).
$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id = " . (int)$id);
When you want to display the object-type data, just loop through $rows and using -> syntax to echo the values.
echo "<ul>";
foreach ($rows as $obj) {
echo '<li>' , $obj->title , ' & ' , $obj->description , '</li>';
}
}
echo "</ul>";
If you have a compelling reason to keep a redundant / restructured copy of the resultset, then you can more simply command php to generate indexes for you.
foreach ($rows as $obj) {
$data[] = ['title' => $obj->title, 'id' => $obj->id];
}
The [] is just like calling array_push(). PHP will automatically assign numeric keys while pushing the associative array as a new subarray of $data.
I've got an 2d array that stores data from my database table then puts it in a json file. And since I'm not calling my column names because it is dynamic, the array is adding it's incrementation (numbers) automatically with the table cell detail, I don't want this.
Here is the json file example
{"0":"1","Fix":"1","1":"Sunday, May 11, 2014","Date":"Sunday, May 11, 2014","2":"FT","Time":"FT","3":"Cardiff City","Home":"Cardiff City","4":"1-2","Score":"1-2","5":"Chelsea","Away":"Chelsea","6":"Cardiff City Stadium (27,716)","Stadium":"Cardiff City Stadium (27,716)"}
I attempted to remove it in php like this
//Select everything in table
$query = mysql_query("SELECT * FROM ".$tablename);
//Storing the data into one arrays witk the ey => value
while($r=mysql_fetch_array($query)){
//Store the data as a 2d array
$json[] = $r;
}
foreach ($json as $key => $value) {
# code...
if(preg_match('/[0-9]/', $key)){
unset($json[$key]);
}else{
}
}
//Display the JSOn data
$o = fopen($tablename.'.json', 'w');
echo fwrite($o, json_encode($json));
fclose($o);
use MYSQL_ASSOC as a second parameter of the mysql_fetch_array() function.
I am fetching values from mysql table. I am then placing the values inside an array and using th php built function json_enconde to convert these values into a json format. I am getting results back but not in the desired format. In the php code you will notice I am using array and fetching values with a foreach loop to place all values inside. As a result I am getting back several json objects. How can I get back just one json object with the corresponding values?
header("Content-type: application/json");
$query = $db_con->prepare("SELECT id, name FROM table");
$query->execute();
$data = $course_query->fetchAll();
$json_data = array();
foreach ($data as $row) {
$json_data[] = array(
$row["id"] => $row["name"]
);
} // foreach ($data as $row) {
echo json_encode($json_data);
Results:
{
1: "Item1"
},
{
2: "Item2"
},
{
3: "Item3"
}
Desired Results:
{
"1":"Item1",
"2":"Item2",
"3":"Item3"
}
change this array( $row["id"] => $row["name"]);
to $json_data[$row["id"] ] = $row["name"] inside the for loop
foreach ($data as $row) {
$json_data[$row["id"] ] = $row["name"];
}
try this
foreach ($data as $row) {
$id=$row["id"];
$json_data[$id] =$row["name"];
}
The problem was that while defining the value in json_data in your foreach loop you are creating an array for every single value, so you are not getting the desired result.
You will need to change your PHP code to create a normal single dimensional array, right now you are creating a multidimensional array. Your PHP should be like this:
header("Content-type: application/json");
$query = $db_con->prepare("SELECT id, name FROM table");
$query->execute();
$data = $course_query->fetchAll();
$json_data = array();
foreach ($data as $row) {
$json_data[$row["id"]] = $row["name"];
} // foreach ($data as $row) {
echo json_encode($json_data);
Notice the change in the foreach loop, we are no longer appending a new array onto the $json_data array(which would create a multidimensional array). This will give you a single dimensional array with the proper key:value pairs. Then when you run the json_encode you will get your desired JSON format.
i want to make a website something like popurls.com, but I will use static data stored in MySQL database. Btw I use php/mysql.
In each list i want to show around 10 links (just like on popurls). In that case, if I would have 20 lists, i would need to make 20 'for' loops (for each particular list).
My question is; is there some better way to print that 20 lists instead of using 20 'for' loops in php.
a for loop or a foreach loop will work fine, but it will be a lot less coding if you just create a single for loop and push content into an array of arrays or an array of strings... you can then do whatever you'd like with the actual content (assuming we're grouping by a column category. I'll use an example that uses an array of strings (and the query that I reference is explained here: http://explainextended.com/2009/03/06/advanced-row-sampling/)
$query = mysql_query([QUERY THAT GETS ALL ITEMS, BUT LIMITS BY EACH CATEGORY]) or die(mysql_error());
$all_items = array();
while($row=mysql_fetch_array($query)){
if (!isset($all_items[$row['category']])){ //if it isn't created yet, make it an empty string
$all_items[$row['category']] = "";
}
$all_items[$row['category']] .= "<li><a href='".$row['url']."'>".$row['title]."</a></li>"; //concatinate the new item to this list
}
Now we have an array where the block of HTML for each section is stored in an array keyed by the name of the category. To output each block, just:
echo $all_items['category name'];
PHP's foreach http://php.net/manual/en/control-structures.foreach.php
Depends a lot on your data input but I could imagine something like this:
<?php
$lists = arrray('list1', 'list2', 'list3');
foreach ($lists as $current) {
$data = fetch_data_from_mysql($current);
foreach ($data as $link) {
echo "Link";
}
}
function fetch_data_from_mysql($current)
{
$list_data = array();
// do whatever is required to fetch the list data for item $current from MySQL
// and store the data in $list_data
return $list_data;
}
You just need two foreach loops. Assuming that you take the data from a mysql table (like you wrote), this could be like this:
$list_query = mysql_query("SELECT * FROM lists";)
while( $list = mysql_fetch_array($list_query) )
{
echo "<h1>{$list['title']}</h1>";
$query = mysql_query("SELECT * FROM entries WHERE list_id = {$list['id']}");
while( $entry = mysql_fetch_array($query) )
{
echo "- {$entry['name']}<br />";
}
}
You can get all the information from the database and parse it into an array, something like
array[<news type1>] = array( link1, link2, link3, etc);
array[<news type2>] = array( link1, link2, link3, etc);
and so on
and on the layout you can use
foreach ($newsCategory AS $categoryLinks) {
foreach ($categoryLinks AS $newsLink) {
<show the link and / or extra data>
}
}
Just store your links in two-dimensional array. That way you'll have to make 1 outer loop (iterating over lists) and 1 inner loop iterating over links in a particular list.
$links = array(
'science' => array('link1', 'link2', ...),
'sports' => array('link1', 'link2'),
// ... and so on
);
foreach ($links as $category => $urls) {
echo "Links in category: $category\n";
foreach ($urls as $url) {
echo $url . "\n";
}
}
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Turn database result into array
Hi guys, can you please help me. How to get an hierarchical php structure from a db table, in php array, or JSON, but with the following format:
[
{
"attributes":{
"id":"111"
},
"data":"Some node title",
"children":[
{
"attributes":{
"id":"555"
},
"data":"A sub node title here"
}
],
"state":"open"
},
{
"attributes":{
"id":"222"
},
"data":"Other main node",
"children":[
{
"attributes":{
"id":"666"
},
"data":"Another sub node"
}
],
"state":"open"
}
]
My SQL table contains the fields: ID, PARENT, ORDER, TITLE
Can you please help me with this? I'm going crazy trying to get this.
Many thanks in advance.
Daniel
Two pass foreach does the trick. This will link all child to their parents recursively.
$structure = array();
foreach( $array as $row ) { //add rows to array by id
$structure[ $row["id"] ] = $row + array( "children" => array() );
}
foreach( $structure as &$row ) { //link children to parents
if( ! is_null( $row["parent"] ) ) {
$structure[ $row["parent"] ]["children"][] =& $row;
}
}
The method you're using in storing your data is called Adjacency List model. To be able to achieve what you require. Follow these steps.
1) Retrieve the parent elements and save them to an array / hash.
2) Iterate through the parent array and retrieve child elements using the id of the parent.
Save the result to an array and append as element of the current parent array using "children" as key.
3) JSON encode the resulting array.
<?php
$sql = "SELECT * FROM yourtable WHERE PARENT is NULL or PARENT = 0";
$result = $db->query($sql); //a valid MySQL database adapter with a
//"query" method which returns the full result set.
$arr = array();
foreach($result as $row) {
$sql = "SELECT * FROM yourtable WHERE PARENT = {$row['id']}";
$result2 = $db->query($sql);
$row["children"] = $result2;
$arr[] = $row;
}
echo json_encode($arr);
?>
For more info about retrieving data hierarchy on these type of table, read Rum's post on Retrieving Data Hierarchies on a SQL Table.
Also, take precaution in this implementation. Although it looks easy to implement, watch out for the number of iterations involving external resource calls, in this case your database server. Iteratively calling queries beats the crap out of it causing performance problems in the future. If that is the case, you can apply a technique similar to Kendall Hopkins (though I'm not sure why he used by-ref call on $row). More info about iterative external resource calls here.
<?php
$sql = "SELECT * FROM yourtable";
$result = $db->query($sql);
$arr = array();
//re-index the result array based on their actual IDs
foreach ($result as $row) {
$arr[$row['ID']] = $row;
}
foreach ($arr as $item) {
if (!empty($item["PARENT"]) && $item["PARENT"] != 0) {
$arr[$item["PARENT"]]["children"][] = $item;
//unset the discovered child item to clean-up array and release memory allocation
unset($arr[$item["ID"]]);
}
}
echo json_encode($arr);
?>