json different format - php

I have a query:
$result = mysql_query("SELECT
Left(Right(Base.inputs.Data_inf,4),3) As 'Datas',
count(Base.Data.Data_ID) As `U_Count`
FROM
Base.Data
WHERE
Base.Data_inputs.info = 'TREE'
GROUP BY ");
$rows = array();
while($r = mysql_fetch_array($result)) {
$row[0] = $r[0];
$row[1] = $r[1];
array_push($rows,$row);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
and the result is:
[["Data1",38],["Data2",13]]
I would like the data look more like:
[{"name":"Data1","data":[38]},{"name":"Data2","data":[13]}]
I was trying to use something like this:
$rows = array();
while($r = mysql_fetch_array($sth)) {
$rows['name'] = $r['Datas'];
while($r = mysql_fetch_array($sth)) {
$rows['data'][] = $r['U_Count'];
}
}
But it doesn't work.
Can anyone help?
THNKS

You can traverse the data and store it as an array.
$rows = array();
while($r = mysql_fetch_array($sth)) {
$rows[] = array('name'=>$r['Datas'],'data'=>array($r['U_Count']));
}

Use mysql_fetch_object() instead of mysql_fetch_array()
while($r = mysql_fetch_object($result)) {
...

Related

PHP: Array to string conversion when retrieving outside function

Good day!
I have a problem here that I can't solve (last 5hrs).
here's my codes:
include 'assets\function\retrieveFunction.php';
$loadGradProgram = array();
$x = count(getCourseInfo());
for($i=0;$i<=$x;$i++){
$loadGradProgram[$i] = getCourseInfo();
}
echo $loadGradProgram[0];
getCourseInfo function
Solution 1:
function getCourseInfo(){
$getInfo = array();
include 'assets\database\connect.php';
$i = 0;
$x = 0;
$sql = "SELECT c.courseID, c.courseCode, c.courseTitle, m.description";
$sql .=" FROM tblcourse as c INNER JOIN tblcoursemajor as m ON c.courseid=m.courseID ORDER BY c.courseID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getInfo[$i] = $row;
$i++;
}
return $getInfo;
}
}
Result: Array to string conversion
Solution 2:
function getCourseInfo(){
$getInfo = array();
$loadInfo = array();
include 'assets\database\connect.php';
$i = 0;
$x = 0;
$sql = "SELECT c.courseID, c.courseCode, c.courseTitle, m.description";
$sql .=" FROM tblcourse as c INNER JOIN tblcoursemajor as m ON c.courseid=m.courseID ORDER BY c.courseID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getInfo[$i] = $row;
$i++;
}
$conn->close();
for($x,$x<=$i;$x++;){
$loadInfo[] = implode(',', $getInfo[$x]);
}
return $loadInfo;
}
}
Result: Still the same
and this line causing error: echo $loadGradProgram[0];
I use echo just to see if the query is working.
if you want a multi-dimmentional array like in w3c documentation, you do it like this :
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getInfo[$i][] = $row['courseID'];
$getInfo[$i][] = $row['courseCode'];
...
$i++;
}
return $getInfo;
then, if you want to diplay an information in the array you can do a foreach loop or a for loop like :
foreach($loadGradProgram as $key => $value) // here the key is useless
{
echo $value[0];
echo $value[1];
}
or directly like this :
echo $loadGradProgram[0][0];
echo $loadGradProgram[0][1];
echo $loadGradProgram[1][0];

Form json using php json_encode failed

By using below code
$data = array();
$sql = "SELECT * FROM list";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data['title'] = $row['title'];
$data['name'] = $row['name'];
}
}
echo json_encode($data);
I got 1 result, I can get full result if I do $data[] = $row['title'], but I want to make the result like this
{'title' : ['title 1','title 2'], 'name':['John','Amy']}
You are overwriting the title in each loop iteration. You need to accumulate all the titles and then set it in your data array.
$data = array();
$sql = "SELECT title FROM mainlist";
$result = $db->query($sql);
$titles = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$titles[] = $row['title'];
}
}
$data['title'] = $titles;
echo json_encode($data);
The easiest away is probably this:
$rows = array();
$sql = "SELECT * FROM list";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
}
echo json_encode($rows);
you could achieve by using group_concat on each of the columns in your query. That way you do not need to loop the result again and add column etc...
$sql = "SELECT group_concat(title) as title,group_concat(name) as name FROM list";
$result = $db->fetch(PDO::FETCH_ASSOC);
echo json_encode($result);
Try this:
$titles = array();
$names = array();
$sql = "SELECT title,name FROM mainlist";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$titles[] = $row['title'];
$names[] = $row['name'];
}
}
echo json_encode(array("title" => $titles, "name" => $names));
UPDATE
Updated my code to let you manage an undefined number of columns as result
$out = array();
$sql = "SELECT * FROM wp_cineteca";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$keys = array_keys($row);
for ($i = 0; $i < count($row); $i++) {
$out[$keys[$i]][] = $row[$i];
}
}
}
echo json_encode($out);

remove last character

i noticed that there are a lot of topics like this in stackoverflow, but the ones that i read are with just 1 variable, and i have two and i'm a little confuse.
so this is my code,
$query = mysql_query("SELECT Provider.provider_id, provider.company_name FROM Provider");
while($row = mysql_fetch_array($query)){
echo "'".$row['provider_id']."':'".$row['company_name']."',";
}
I am using this to generate javascript code for Jeditable.
I need to take out the last comma, so I can wrap up with the rest of the code...
I like to use an array:
$query = ...;
$out = Array();
while($row = mysql_fetch_assoc($query)) {
$out[] = "'".$row['provider_id']."':'".$row['company_name']."'";
}
echo implode(",",$out);
It looks like you're trying to output some kind of JSON though, so perhaps you could use:
$query = ...;
$out = Array();
while($row = mysql_fetch_assoc($query)) {
$out[$row['provider_id']] = $row['company_name'];
}
echo json_encode($out);
So i usually just stack things like this into an array and then implode:
$parts = array();
while($row = mysql_fetch_array($query)){
$parts[] = "'".$row['provider_id']."':'".$row['company_name']."'";
}
echo implode(',', $parts);
That said it looks like youre outputting the body of a JSON string. If so you shouldnt manually build it you should use json_encode instead.
$data = array();
while($row = mysql_fetch_array($query)){
$data[$row['provider_id']] = $row['company_name'];
}
echo json_encode($data);
$query = mysql_query("SELECT Provider.provider_id, provider.company_name FROM Provider");
$result = "";
while($row = mysql_fetch_array($query)){
$result .= "'".$row['provider_id']."':'".$row['company_name']."',";
}
$result = rtrim($result, ',');
OR
$query = mysql_query("SELECT Provider.provider_id, provider.company_name FROM Provider");
$result = array;
while($row = mysql_fetch_array($query)){
$result[] = "'".$row['provider_id']."':'".$row['company_name']."',";
}
$result = implode(',' $result);
OR
get count of records (mysql_num_rows($query)) and when you hit last row just do what you want

Echo all variable from while loop

I hava a while loop that throught to databases records. Like this:
$query = mysql_query("SELECT * FROM table");
while($articles = mysql_fetch_array($query)){
// something happen here
}
How can I echo each $articles out of the while loop ? So I don't want to have something like
while(...){
echo $articles['article_name'];
}
How can I save all the $articles['article_name'] into an array an echo them back ?
How about this:
$articleList = array();
while(...){
$articleList[] = $articles['article_name'];
}
That will put everything in the array $articleList for you.
You can do something like:
$articles = array();
while ($art = mysql_fetch_array($query)) {
$articles[] = $art;
}
print_r($articles);
$i=0; $articles = array();
$query = mysql_query("SELECT * FROM table");
while($articles[] = mysql_fetch_array($query)){
echo $articles['article_name'][$i];
$i++;
}
$query = mysql_query("SELECT * FROM table");
while($articles = mysql_fetch_array($query)){
$names[] = $articles['article_name'];
}
echo 'array of names are :';
print_r($names);

Set value of multidimensional array

I'm currently adding fileID to idarray[] and then do a foreach. But in addition to fileID I also need serverID and id in the array and the foreach, how do I do this? So basically I need to find out how to add 2 more values to the array and then also use those extra values in the foreach.
$result = mysql_query("SELECT * FROM redundfiles WHERE removed=1");
while($row = mysql_fetch_array($result))
{
$idarray[] = $row['fileID'];
}
foreach ($idarray as $value)
{
$result = mysql_query("SELECT * FROM redundfiles WHERE fileID=$value AND removed=0 AND serverID=$XXXserverIDhereXXX");
while($row = mysql_fetch_array($result))
{
$sql = "DELETE FROM redundfiles WHERE id='".$XXXidhereXXX."' ";
mysql_query($sql) or die(mysql_error());
}
}
Why not just store the whole row into an array?
$rowarray[] = array();
$result = mysql_query("SELECT * FROM redundfiles WHERE removed=1");
while($row = mysql_fetch_array($result))
{
$rowarray[] = $row;
}
foreach ($rowarray as $row)
{
$fileid = $row['fileID'];
$serverid = $row['serverID'];
$result = mysql_query("SELECT * FROM redundfiles WHERE fileID=$fileid AND removed=0 AND serverID=$serverid");
while($row = mysql_fetch_array($result))
{
$sql = "DELETE FROM redundfiles WHERE id='".$XXXidhereXXX."' ";
mysql_query($sql) or die(mysql_error());
}
}
But really, your whole code piece here is a mess. You can accomplish this way more efficiently using JOINs.

Categories