JSON-encode several arrays - php

I'm using JSON_encode to send data to a js file for tracks. A user could have one or several tracks so that's where the problem lies. Not sure how to organise my array to allow for several arrays. I can't use an array within an array since all the JSON data needs to be separated preferably so there will be something like;
track1 {ID:110232....}
track2 {ID:21402....}
What I have now works fine if there is just one track.
$ID = $_GET['ID'];
$result = mysql_query("SELECT * FROM tracks WHERE ID = '$ID' ORDER BY timestamp DESC");
while($row = mysql_fetch_array($result)){
$T_ID = $row['T_ID'];
$T_url = $row['url'];
$T_name = $row['name'];
$T_timestamp = $row['timestamp'];
$arr = array('T_ID' => $ID,'T_name' => $T_name, 'T_url' => $T_url, 'T_timestamp' => $T_timestamp );
echo json_encode($arr);
}

Why can't you use an (associative) array inside an container array like this:
$cont = array();
while($row = mysql_fetch_array($result)){
$T_ID = $row['T_ID'];
$T_url = $row['url'];
$T_name = $row['name'];
$T_timestamp = $row['timestamp'];
$arr = array('T_ID' => $ID,'T_name' => $T_name, 'T_url' => $T_url, 'T_timestamp' => $T_timestamp );
$cont[] = $arr;
}
echo json_encode($cont);
This results in a JSON structure like this, which keeps all your tracks in separate objects:
[
{'T_ID': 1, 'T_name': 1, ... },
{'T_ID': 2, 'T_name': 2, ... },
{'T_ID': 3, 'T_name': 3, ... },
...
]
As noted in the comments you should switch to PDO or mysqli- functions, but this doesn't matter for the problem at hand..

Related

How to combine two or more mysql array in one

I have two table that has multiple rows. I want to combine those two tables rows into one long array which will be identified as one array
I wrote this code
$posts_sql = $db->query("SELECT * FROM posts WHERE id < $lastpost AND position = submitter order by id DESC LIMIT 5");
$posts_all = $db->fetch_all($posts_sql);
foreach($posts_all as $key => $posts_row){
$users_sql = $db->query("SELECT username,firstname,lastname,avatar FROM users WHERE username = '".$posts_row['submitter']."'");
$users_all = $db->fetch_assoc($users_sql);
$data[] = $posts_row;
$data[] = $users_all;
}
echo json_encode($data);
It makes duplicate arrays doesn't right...
That's how my result show
[{
"id":"39",
"hash":"070fcc8e73ba5f549f87",
"post":"hello\n",
"files":"",
"location":",
"GB","status":"1",
"position":"dabblos",
"submitter":"dabblos",
"source":"text",
"ip":"37.130.227.133",
"stamp":"1390197699"
},
{
"username":"dabblos",
"firstname":"dabb",
"lastname":"los",
"avatar":"no_avatar.png"
}]
please help me make it just one long array
I would like to see the output looks like this
{
"id":"39",
"hash":"070fcc8e73ba5f549f87",
"post":"hello\n",
"files":"",
"location":",
"GB","status":"1",
"position":"dabblos",
"submitter":"dabblos",
"source":"text",
"ip":"37.130.227.133",
"stamp":"1390197699"
"username":"dabblos",
"firstname":"dabb",
"lastname":"los",
"avatar":"no_avatar.png"
}
look at this,i have taken example values, it is working fine as you wanted
$arr=array(array("abc"=>"1","def"=>"2"),array("abcc"=>"11","deff"=>"22"));
echo json_encode($arr);
$final = array();
foreach($arr as $item) {
$final = array_merge($final, $item);
}
print_r($final);
output
[{"abc":"1","def":"2"},{"abcc":"11","deff":"22"}]//json_array
Array ( [abc] => 1 [def] => 2 [abcc] => 11 [deff] => 22 )//final array
UPDATE
json_encode the final array and you'll get the desired result
echo json_encode($final);
output
{"abc":"1","def":"2","abcc":"11","deff":"22"}
Untested:
$posts_sql = $db->query("SELECT * FROM posts WHERE id < $lastpost AND position = submitter order by id DESC LIMIT 5");
$posts_all = $db->fetch_all($posts_sql);
foreach($posts_all as $key => $posts_row) {
$users_sql = $db->query("SELECT username,firstname,lastname,avatar FROM users WHERE username = '".$posts_row['submitter']."'");
$users_all = $db->fetch_assoc($users_sql);
$data[] = $posts_row;
foreach($users_all as $user)
$data[] = $user;
}
}
echo json_encode($data);
// when you use json_decode use the 'true' flag as in
// $decodedJson = json_decode($json, true);
Merge them before you json_encode them:
$data[] = $posts_row;
$data2[] = $users_all;
$result = array_merge($data,$data2);
echo json_encode($result);

Show selected data as array value instead of string

I'm trying to put data from my database into seperate arrays within another array. This works but when I'm trying to fetch the 'user_id' information, it only shows one number so it works like a string. How can I get it to work like an array and get the entire user_id?
$fetch = mysqli_query($con, "SELECT * FROM spotify_userdata");
$return_arr = [];
while ($row = mysqli_fetch_array($fetch, MYSQL_ASSOC)) {
$return_arr[] = array(
$row_array['user_id'] = $row['user_id'],
$row_array['name'] = $row['name'],
$row_array['artists'] = $row['artists'],
);
}
$user = json_encode($return_arr[0]);
echo $user[2];
This code returns 1 so it show the third number of the user_id. How can I get it to show the entire user_id like this: 111434343
You have many things in your code that's wrong:
Remove the last array item's comma
Change
$return_arr = [];
To
$return_arr = array();
3.Add:
$row_array = array()
at the begginning of all that code
At the end your code must be like this:
$fetch = mysqli_query($con, "SELECT * FROM spotify_userdata");
$row_array = array();
while ($row = mysqli_fetch_array($fetch, MYSQL_ASSOC)) {
$return_arr = array(
$row_array['user_id'] = $row['user_id'],
$row_array['name'] = $row['name'],
$row_array['artists'] = $row['artists'],
);
}
$user = json_encode($return_arr[0]);
According to your code you should use:
echo $user['user_id'];
But the real problem is - where is $row_array initialized?!?
And even bigger problem - why use "=" inside array creation in the while ... it seems to me that "=>" would fit better, don't you think?

Mysql result into 2d array php

$thearray = array
(
//(0)ID, (1)NAME, (2)LOCATION, (3)PHONE
array("0","Name 1","Nowhere 11","0004444"),
array("1","Name 2","Everywhere 11","0005555"),
array("2","Name 3","ThisPlace 11","0002222"),
array("3","Name 4","NoPlace 11","0003333"),
array("4","Name 5","ThatPlace 11","0001111")
);
This is how I used to store my information
I would then run through them to find what I needed
and display them using for example
echo $thearray[$i][4]
I want to do the same thing except store that information in Mysql
This is how far I've gotten but I keep getting strange errors and I cant output from the array
This is how far I've gotten
$result = $db->query("SELECT * FROM table");
$thearray = array();
while($thearray = $result->fetch_assoc()){
$thearray[] = $thearray;
}
For some reason this isn't working for me, its like it isnt in a 2d array like I have above :S I can't simply echo it like I did before.
Well first of all
while($thearray = $result->fetch_assoc()){
$thearray[] = $thearray;
}
Will keep overwriting the array and get very confused
try
while($row = $result->fetch_assoc()){
$thearray[] = $row;
}
The array returned from your query is no longer a simple array, it is a associative array
i.e. it will look something like this:
$new_array = array
(
//(0)ID, (1)NAME, (2)LOCATION, (3)PHONE
array('ID' => "0", 'NAME' => "Name 1", 'LOCATION' => "Nowhere 11", 'PHONE' => "0004444"),
array('ID' => "1", 'NAME' => "Name 2", 'LOCATION' => "Nowhere 22", 'PHONE' => "0005555"),
etc
);
So now when you want to use it you will have to use this sort of construct
$name = $new_array[$i]['NAME']
$location = $new_array[$i]['LOCATION']
etc
or
<?php echo $new_array[$i]['NAME']; ?>
<?php echo $new_array[$i]['LOCATION'] ?>
etc

PHP multidimensional to flat array (changing key->value)

This is a problem that I come across frequently when using PHP to query mysql data, and I would like to know if there is a more efficient solution. When I only need two columns of data, for instance the columns 'id' and 'price', I prefer this 'flat' format:
array(
id 1 => price 1,
id 2 => price 2,
id 3 => price 3,
...
);
or in json:
[{"id 1":"price 1"},{"id 2":"price 2"},{"id 3":"price 3"}, ...]
And my usual solution is to loop twice, like so:
require_once('server/connection.php');
$info = mysql_query("SELECT id, price FROM table");
$array1 = array();
while ($row = mysql_fetch_assoc($info)) {
$array1[] = array(
'id' => $row['id'],
'price' => $row['price']
);
}
mysql_close($con);
$array2 = array();
foreach ($array1 as $key => $value) {
$array2[$key][$value['id']] = $value['price'];
}
print json_encode($array2);
which does work, but I think this code is too lengthy for its purpose, and there should be a better way -- so that I only have to loop one array. Any suggestions?
You can simplify your loop to this
while ($row = mysql_fetch_assoc($info)) {
$array1[] = array(
'id '.$row['id'] => 'price '.$row['price']
);
}
print json_encode($array1);
$result = array();
while ($row = mysql_fetch_assoc($info)) {
$result[$row['id']] = $row['price'];
}
print_r($result);
require_once('server/connection.php');
$info = mysql_query("SELECT id, price FROM table");
$array1 = array();
while ($row = mysql_fetch_assoc($info))
$array1[$row['id']] = $row['price'];
mysql_close($con);
print json_encode($array1);
NOTE: your $array2 is a two dimensional array. If it works for you, you need to change your javascript code to handle following flat format i.e. the above code produce
[{"id 1":"price 1"},{"id 2":"price 2"},{"id 3":"price 3"}, ...]

Return MySQL rows in array

I've been working on a OOP method that is supposed to return the rows of a MySQL query. I have to have the data array in the format:
$rows = array('row'=> rownum, 'fld1'=> fldval .... 'fldn' => fldval);
What I have encountered are the two problems of either:
returns
$rows = array('0'=>fldval, 'fld1'=> fldval .... 'n'=> fldval, 'fldn' => fldval);
or single row of
$rows = array('fld1'=> fldval .... 'fldn' => fldval);
Little frustrated as every PHP mysql function I have tried has some sort to goofy crap flaw and will not do a straight out process.
I assume there is a good example somewhere, that can get me past the crap limitations, but haven't found anything useful yet!
I've tried all of the following:
$row = mysql_result($db_res,$n);
$row = mysql_fetch_array($db_res);
$row = mysql_fetch_assoc($db_res);
$row = mysql_fetch_object($db_res);
$row = mysql_fetch_row($db_res);
None have worked successfully! For getting out the bogus "numeric" array entries. I wrote:
foreach ($row as $k => $v)
if (is_numeric($k)) { continue; }
$result[$k] = $v;
} // end foreach $row
$row = array_push($row, 'row'=>$rownum, $result);
Hoping someone has a link.
$list = array();
$query = "SELECT value FROM table";
$resource = mysql_query($query);
while($row = mysql_fetch_assoc($resource))
{
$list['fld' . (1 + count($list))] = $row['value'];
}
$list = array('row' => count($list)) + $list;
if table have 3 row, the code above is going to give you a array like:
array(
'row' => 3,
'fld1' => 12,
'fld2' => 34,
'fld3' => 56
);

Categories