I've been searching everywhere for a definitive answer to what seems to be a really simple task - unfortunately all the solutions I can find (and there are a lot) use mysql_fetch_assoc which is deprecated.
All I'm trying to do is to take a two column set of results from a database and echo in JSON format - I've managed everything fine except for one bit - I can't work how to get the values in to a two dimensional array (two column array) using array_push. I just end up with my two column values merged in to one array. Here's a stripped version of what I've done:
header('Content-Type: application/json');
$mostPopularStm = $sparklyGenericPdoObj->prepare("SELECT views, thing FROM X");
$mostPopularStm->execute();
$mostPopularRS = $mostPopularStm->fetchAll();
echo '{data:';
$mostPopularJson = array();
foreach ($mostPopularRS as $mostPopularItem)
{
array_push($mostPopularJson, $mostPopularItem["views"], $mostPopularItem["thing"]);
}
echo json_encode($mostPopularJson);
echo '}';
This is producing output like this:
{data:["Monkeyface","43","Giblets","25","Svelte","22","Biriani","21","Mandibles","20"]}
But what I need is this:
{data:["Monkeyface":"43","Giblets":"25","Svelte":"22","Biriani":"21","Mandibles":"20"]}
I know I can create something manually to do this, using json_encode to format the string on each loop but it seems inefficient.
Any pointers would be hugely appreciated!
Your current array is like
array(0 => 'Monkeyface', 1 => 43, /* ... */);
but you need like
array('Monkeyface' => 43, /* ... */);
Replace
array_push($mostPopularJson, $mostPopularItem["views"], $mostPopularItem["thing"])
By
$mostPopularJson[$mostPopularItem["thing"]] = $mostPopularItem["views"];
And
echo '{data:';
echo json_encode($mostPopularJson)
echo '}';
Better to use:
echo json_encode(array('data' => $mostPopularJson));
As kingkero said, you will never get your expected result because it is invalid:
{data:["Monkeyface":"43" ...
Correct:
{ "data": { "Monkeyface": "43" ...
Compose your array like so:
$mostPopularJson [$mostPopularItem["thing"]] = $mostPopularItem["views"];
Related
I'm creating this JSON thingy and I need to remove the last comma from it. (yes I know I could do a simple way instead of making the json myself, but I need it to be like this {"1":0,"2":4,"3":1.5}) So how can I do it? (And yes I have a working way in the code but it doesent display it like I need it.)
<?php
require 'dbConnect.script.php';
$query="SELECT * FROM `trash`";
if($is_query_run=mysql_query($query)){
print "{";
while($query_execute=$query_execute=mysql_fetch_assoc($is_query_run)){
echo '<tr><td>"'.$query_execute['id'].'"</td>:<td>'.$query_execute['weight'].',</td></tr>';
//$rows = array();
//$rows[] = $query_execute;
//print json_encode($rows);
}
print "}";
}
else{
echo "query notexecuted";
}
?>
In your example, you can simply create an array:
$array = ["1" => 0, "2" => 4, "3" => 1.5];
$json = json_encode($array);
Since this array doesn't start with a zero (which indexed arrays does), this would give you your desired result.
If you want to start with a zero, and still get an object back:
$array = ["0" => 2, "1" => 0, "2" => 4, "3" => 1.5];
you can use the option JSON_FORCE_OBJECT as a second parameter, like this:
$array = ["0" => 2, "1" => 0, "2" => 4, "3" => 1.5];
$json = json_encode($array, JSON_FORCE_OBJECT);
This will give you:
{
"0": 2,
"1": 0,
"2": 4,
"3": 1.5
}
Read more here: http://php.net/manual/en/function.json-encode.php
It's seldom a good idea to build your own encoders/decoders for things like this. It usually gets quite complicated pretty quick, and you will spend most of your time straighten out bugs and get stuck on edge cases. It's better to read up on the native functions. They have been tried and tested for years, and are often much better in regards of performance.
Whilst I concur json_encode is the nicest solution for producing JSON. To produce a nice comma separated output you could use the implode function.
Set-up your elements in an array, so for example:
$data = array('"1":0', '"2":4', '"3":1.5');
Then use implode like this
$output = implode(',', $data);
Which will give you an output of the data elements in the array as a comma separated list
if($is_query_run=mysql_query($query)){ //Here you execute the query
while($query_execute=$query_execute=mysql_fetch_assoc($is_query_run)){ //Here you get one row from execution result
$rows = array(); //You create array into $rows, what was in $rows before will be wiped
$rows[] = $query_execute; // You insert one row you just fetch from result to $rows
print json_encode($rows); // You encode $rows (which always has only one element as you wipe it every iteration)
}
}
So, create array before loop, and encode that array after loop, adding elements to array inside a loop is ok.
-Mr_KoKa #LinusTechTips.com
I have read a-lot of answers on this but they don't seem to be working.
I have the following code:
$amountoflikes=mysql_query("SELECT * FROM `uc_likes` WHERE `dwable` = '372'");
This returns the following:
If I wanted to echo the value of dwable in the 2nd row for instance (not involving the initial query).
I've tried:
while($row3 = mysql_fetch_assoc($amountoflikes)){
$json[] = $row3;
}
echo json_encode($json);
But this returns null.
I'm currently using PHP 5.5 (native).
I'm not using MySQLi or MySQL PDO.
Can someone tell me where I'm going wrong. Ideally I'd prefer not to use a loop but I don't know if that's possible.
Thanks!
Try declaring $json as an array above the while:
$json = array();
declare your array as follows
$json = array();
and see if you have results before your result
if ($amountoflikes)
{
while(){...}
}
I'm new to PHP and I was asked to write a function that accepts an array as a parameter and then prints the array in reverse order. Here is what I have so far:
<?php
function RevOrder ($arr1) {
$arr1 == array();
echo array_reverse($arr1);
}
RevOrder (array(1,4,2,5,19,11,28));
?>
It is supposed to output 28, 11, 19, 5, 2, 4, 1 but I keep getting an array to string conversion error.
echo expects a string while you are passing an array, hence the array to string conversion error. It also looks like you are not properly checking if the param passed is an array. Try this:
<?php
function RevOrder($arr1) {
if (is_array($arr1)) {
return array_reverse($arr1);
}
return false;
}
$reversedArray = RevOrder(array(1,4,2,5,19,11,28));
// Option 1
print_r($reversedArray);
// Option 2
echo(implode(', ', $reversedArray));
<?php
function RevOrder (array $arr1) {
echo implode(", ", array_reverse($arr1));
}
RevOrder (array(1,4,2,5,19,11,28));
But note that this isn't particularly good design - your functions should do one thing. In this case you should instead write a function to print an array according to your liking and then pass it reversed array. Although in this case I guess it's ok to have a helper function for printing the array in reversed order but when you're doing something more complicated you should consider this.
EDIT:
You could do something like this:
function printArray(array $arr){
echo implode(", ", $arr);
}
printArray(array_reverse($arr));
As for why you can't just echo array see this
Arrays are always converted to the string "Array"; because of this,
echo and print can not by themselves show the contents of an array. To
view a single element, use a construction such as echo $arr['foo'].
See below for tips on viewing the entire contents.
Also I added type-hints for array so that when you pass something that's not an array you get an error.
Confusing title, the basics are that I'm saving a fully sorted and ordered multidimensional array from a script and into MySQL. I then, on another page, pull it from the database and unserialize it, and then proceed to print it out with this,
$s = "SELECT * FROM gator_historical_data WHERE channelid = '{$chanid}'";
$r = $link->query($s);
$comboarray = array();
while ($row = mysqli_fetch_assoc($r)) {
$comboarray[] = unserialize($row['dataarray']);
}
foreach ($comboarray as $item) {
$desc = $item['content']['description'];
$title = $item['content']['title'];
$datetime = $item['datetime'];
// ... ^^^ problems getting array data
}
The problem is that it doesn't take the full array from MySQL, only the first entry and thus only prints the first 'array'. So where the returned value from dataarray looks like this (var_dump): http://pastebin.com/raw.php?i=Z0jy55sM the data stored into the unserialized $comboarray only looks like this (var_dump): http://pastebin.com/raw.php?i=Ycwwa924
TL;DR: Pulling a serialized multidimensional array from a database, unserializing and it loses all arrays after the first one.
Any ideas what to do?
The string you've got is a serialized string plus something more at the end that is also a serialized string again and again:
a:3:{s:6:"source";s:25:"World news | The Guardian";s:8:"datetime ...
... story01.htm";}}a:3:{s:6:"source";s:16:"BBC News - World";
^^^
This format is not supported by PHP unserialize, it will only unserialize the first chunk and drop everything at the end.
Instead create one array, serialize it and store that result into the database.
Alternatively you can try to recover for the moment by un-chunking the string, however in case the paste was done right, there are more issues. But on the other hand the paste obvious isn't the done fully correct.
I am requesting my output look like this:
Response
{
error_num: 0
error_details:
[
{
"zipcode": 98119
},
{
"zipcode": 98101
}
]
}
The values are irrelevant for this example.
My code looks like this:
$returndata = array('error_num' => $error_code);
$returndata['error_details'] = $error_msg;
$temp_data = array();
$temp_value = '';
foreach ($zipcodes_array as $value) {
//$temp_data['zipcode'] = $value;
//$temp_value .= json_encode($temp_data);
$temp_value .= '{"zipcode":$value},';
}
//$returndata['test'] = $temp_value;
$returndata['zipcodes'] = $temp_value;
echo json_encode($returndata);
My output varies depending on my different attempts (which you can see with the commented out things) but basically, I don't understand how the 3rd part (the part with the zipcodes) doesn't have a key or a definition before the first open bracket "["
Here is the output for the code above:
{"error_num":0,"error_details":"","zipcodes":"{\"zipcode\":11111},{\"zipcode\":11112},{\"zipcode\":11113},{\"zipcode\":22222},{\"zipcode\":33333},{\"zipcode\":77325},{\"zipcode\":77338},{\"zipcode\":77339},{\"zipcode\":77345},{\"zipcode\":77346},{\"zipcode\":77347},{\"zipcode\":77396},{\"zipcode\":81501},{\"zipcode\":81502},{\"zipcode\":81503},{\"zipcode\":81504},{\"zipcode\":81505},{\"zipcode\":81506},{\"zipcode\":81507},{\"zipcode\":81508},{\"zipcode\":81509},"}
Obviously i did not show the variables being filled/created because its through MySQL. The values are irrelevant. Its the format of the output i'm trying to get down. I don't understand how they have the "zipcode": part in between {} brackets inside another section which appears to be using JSON_ENCODE
It is close but see how it still has the "zipcodes": part in there defining what key those values are on? My question is, is the "response" above being requested by a partner actually in JSON_ENCODE format?? or is it in some custom format which I'll just have to make w/out using any json features of PHP? I can easily write that but based on the way it looks in the example above (the response) I was thinking it was JSON_ENCODE being used.
Also, it keeps putting the \'s in front of the " which isn't right either. I know it's probably doing that because i'm json_encode'ing a string. Hopefully you see what i'm trying to do.
If this is just custom stuff made to resemble JSON, I apologize. I've tried to ask the partner but I guess i'm not asking the right questions (or the right person). They can never seem to give me answers.
EDIT: notice my output also doesn't have any [ or ] in it. but some of my test JSON_ENCODE stuff has had those in it. I'm sure its just me failing here i just cant figure it out.
If you want your output to look like the JSON output at the very top of your question, write the code like this:
$returndata = array('error_num' => $error_code);
$returndata['error_details'] = array();
foreach ($zipcodes_array as $value) {
$returndata['error_details'][] = array('zipcode' => (int)$value);
}
echo 'Response ' . json_encode($returndata);
This will return JSON formatted like you requested above.
Response
{
error_num: 0
error_details:
[
{
"zipcode": 98119
},
{
"zipcode": 98101
}
]
}
Can you just use single ZipCode object as associative array, push all your small ZipCode objects to the ZipCodes array and encode whole data structure. Here is the code example:
$returndata = array(
'error_num' => $error_code,
'error_details' => array()
);
foreach ($zipcodes_array as $value) {
$returndata['error_details'][] = array('zipcode' => $value);
}
echo json_encode($returndata);