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
Related
I would like to expand a string with one or more values which come from an array.
Desired result:
http://example.com/search/key=["Start", "USA", "Minneapolis"]&shift=false
Array:
array(2) {
[0]=>
string(8) "USA"
[1]=>
string(4) "Minneapolis"
}
PHP Code:
$myArr = ("USA", "Minneapolis");
$string = 'http://example.com/search/key=["Start",' .$myArr[0]. ']&shift=false';
Gives me this result: http://example.com/search/key=["Start", "USA"]&shift=false
How can I make it more dynamic so that more than one value can be added? I know I somehow have to use a foreach($myArr as $i){...} and concatenate the values via $string += but because my variable is in the middle of the string I'm kinda stuck with this approach.
Try the following:
$myArr = array("USA", "Minneapolis");
$string = 'http://example.com/search/key=["Start", "' . implode('", "', $myArr) . '"]&shift=false';
This will provide the expected output using implode.
Something isn't right here. You are trying to pass array data through a querystring but not in a valid array structure. This means you are either not using it as an array on the next script and you are going to having to chop and hack at it when the data gets there.
I'll make the assumption that you would like to clean up your process...
Declare an array of all of the data that you want to pass through the url's query string, then merge the new key values into that subarray. Finally, use http_build_query() to do ALL of the work of formatting/urlencoding everything then append that generated string after the ? in your url. This is THE clean, stable way to do it.
Code: (Demo)
$myArr = ["USA", "Minneapolis", "monkey=wren[h"];
$data = [
'key' => [
'Start'
],
'shift' => 'false'
];
$data['key'] = array_merge($data['key'], $myArr);
$url = 'http://example.com/search/?' . http_build_query($data);
echo "$url\n---\n";
echo urldecode($url);
Output:
http://example.com/search/?key%5B0%5D=Start&key%5B1%5D=USA&key%5B2%5D=Minneapolis&key%5B3%5D=monkey%3Dwren%5Bh&shift=false
---
http://example.com/search/?key[0]=Start&key[1]=USA&key[2]=Minneapolis&key[3]=monkey=wren[h&shift=false
*the decoded string is just to help you to visualize the output.
Then on your receiving page, you can simply and professionally access the $_GET['key'] and $_GET['shift'] data.
If you have a legitimate reason to use your original malformed syntax, I'd love to hear it. Otherwise, please use my method for the sake of clean, valid web development.
Recently I had some experience with converting mysql query results into json for a quiz system. Query results contain set of questions and related anwsers to them. The implemented procedure aims to put those questions and answers into multidimensional array and then convert it into json to build quiz db. I've ready to use JS procedure (quiz module) that works with below mentioned JSON structure. But to build this structure I'm stuck with the following php procedure:
Code in PHP:
$query = "SELECT s1.question, s2.answers, s2.correct
FROM `questions` s1, `answers` s2
WHERE s1.id=s2.questionid AND s1.courseid=".$_POST['courseid']."";
$result = mysqli_query($mysqli, $query) or die ("<b>Select failed:</b> ".mysqli_error($mysqli));
$final_quiz = array();
$final_quiz['introduction'] = "Introduction text goes here";
while ($rows = mysqli_fetch_assoc($result_quiz)) {
$final_quiz['questions']['question'] = $rows['question'];
$final_quiz['questions']['question']['answers'] = array($rows['answers'], "correct"=> $rows['correct']);
}
// convert to JSON
$json = json_encode($final_quiz);
echo $json;
Expected JSON Output:
{
"introduction":"Some introductory text here",
"questions":[
{
"question":"Question number one here?",
"answers":["some incorrect answer", "a correct answer", "another incorrect answer"],
"correct":1}, // indicates an array key that is relates to keys in "answers"
...
]
}
How to organize multidimensional array in order to get above mentioned json structure? Any help would be appreciated.
UPDATES
The values in correct keys are indexes of the answers keys, i.e. if we have "correct":1 that would mean second value of answers key. Correct values for answers that come from MySQL are boolean (TRUE/FALSE). So, before putting all answers in answers_array_key as a set of answers one should remember newly assigned index array for the answer with TRUE value put that index array in correct_array_key as value. An example:
....
"answers":[0:"some incorrect answer", 1:"a correct answer", 2:"another incorrect answer"],
"correct":1}, // this is correct answer key
....
Hope that will that will explain the idea of desired json sturcture mentioned above.
I think this will produce the result you want.
while ($rows = mysqli_fetch_assoc($result_quiz)) {
$final_quiz['questions'][]= array(
'question' => $rows['question'],
'answers' => array($rows['answers']),
'correct'=> $rows['correct']
);
}
In your code, you are overwriting a single element of that array instead of appending the other questions
You can try to use the php json_encode command. (link on php.net -> http://php.net/manual/it/function.json-encode.php)
The link show some example of array structure. On php.net it says it works with each type of structure (not resources).
Edit: as i see you already use this command, but how is the actual output? How much is different from your desired one?
I believe this will solve it for you (I've used an array to test, I hope I got the question right).
You will need to change the foreach loop back to your while loop.
I might have used a bit of different naming, you might need to change a thing or 2 to match your exact names:
<?php
$tmp = array (
array("question"=> "this is a q", "answer"=>"incorrect", "correct" => false),
array("question"=> "this is a q", "answer"=>"incorrect1", "correct" => false),
array("question"=> "q1", "answer"=>"correct", "correct" => true),
array("question"=> "q1", "answer"=>"incorrect", "correct" => false),
array("question"=> "q1", "answer"=>"incorrect1", "correct" => false),
array("question"=> "this is a q", "answer"=>"incorrect1", "correct" => false),
array("question"=> "this is a q", "answer"=>"incorrect2", "correct" => false),
array("question"=> "this is a q", "answer"=>"correct", "correct" => true),
array("question"=> "this is a q", "answer"=>"incorrect3", "correct" => false)
);
$QAndA = array();
foreach ($tmp as $t){
if (!isset($QAndA[$t['question']]['answers']))
$QAndA[$t['question']]['answers'] = array();
$QAndA[$t['question']]['answers'][] = $t['answer'];
if ($t['correct'])
$QAndA[$t['question']]['correct'] = count($QAndA[$t['question']]['answers']) -1;
}
foreach ($QAndA as $q => $data){
$final_quiz['questions'][] = (object)array("question" => $q,
"answers" => $data['answers'],
"correct" => $data['correct']);
}
$json = json_encode($final_quiz);
echo $json;
?>
Result:
{
"questions": [{
"question": "this is a q",
"answers": ["incorrect", "incorrect1", "incorrect1", "incorrect2", "correct", "incorrect3"],
"correct": 4
}, {
"question": "q1",
"answers": ["correct", "incorrect", "incorrect1"],
"correct": 0
}]
}
I do want to apologize for the naming conventions here and the somewhat brute attitude this code presents, but it is very late here;
Add one counter $i and try the below code:
$i = 0;
while ($rows = mysqli_fetch_assoc($result_quiz)) {
$final_quiz['questions'][$i] = array(
'question' => $rows['question'],
//'answers' => $rows['answers'], UPDATE THIS LINE
'answers' => array(
'1' => $rows['answers'][1],
'2' => $rows['answers'][2],
'3' => $rows['answers'][3])
// Why I started from index one? if index is consecutive from 0 to n
// will remove the index in JSON, so start indexing from 1 and make some changes in ur code
'correct' => $rows['correct']
);
$i++;
}
this will work
I tried this code
$jsonlogcontents='{"buildings":"townhall","Army":{ "Paladins":{ "325648":0, "546545":4 }, "Knights":{ "325648":-2, "546545":0 } } }';
$phpArray = json_decode($jsonlogcontents, false);
echo $phpArray->buildings;
echo $phpArray->Army;
This is just a sample of my code, the JSON file is too large to include and has sensitive information. The problem I'm having is I can't get the value or print the value of
$phpArray->Army
It give's me an error. I can however print or get the value of
$phpArray->buildings
I'm thinking that when you decode a JSON file/contents in PHP, you can't get/print/store the value of a 'key' that has more set of info (more { and }) or brackets in it. You can only print/get values for keys who's value's contain only 1 value and nothing else.
If this is the case, what can I do to get the contents of the key that has more JSON codes in it. Also, how can I convert the contents of a key that has more JSON info in it into a string? the conversion is so I can display the value of that key to the page or echo it
The error is because Army is an object, and echo doesn't know how to convert it to a string for display. Use:
print_r($phpArray->Army);
or:
var_dump($phpArray->Army);
to see its contents.
P.S. $phpArray not an array but an object.
For Army however, I will need to do another json_decode() for that.
You don't. json_decode() decodes the entire structure in one call, into one large object (or array). No matter how deeply nested the data is, you call json_decode() once and you're done. That's why Army is not a JSON string any more.
When you are adding false as the second parameter to the json_encode it will updating all array to the sdClass empty objects.In this way you can the main array as the object
<?php
$json = '{
"buildings": "townhall",
"Army": {
"Paladins": {
"325648": 0,
"546545": 4
},
"Knights": {
"325648": -2,
"546545": 0
}
}
}';
$array = json_decode($json, true);
$object = (object)$array;
var_dump($object->Army);
?>
OUTPUT
array(2) {
["Paladins"]=>
array(2) {
[325648]=>
int(0)
[546545]=>
int(4)
}
["Knights"]=>
array(2) {
[325648]=>
int(-2)
[546545]=>
int(0)
}
}
Working Demo
It's because the output from your json_decode looks like this:
object(stdClass)(
'buildings' => 'townhall',
'Army' => object(stdClass)(
'Paladins' => object(stdClass)(
325648 => 0,
546545 => 4
),
'Knights' => object(stdClass)(
325648 => -2,
546545 => 0
)
)
)
Army is a standard object so it can't know how to echo it. You can however var_dump it:
var_dump($phpArray->Army);
The easiest solution is to treat it as a normal array with:
$phpArray = json_decode($jsonlogcontents, true);
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"];
I've been using a few javascript libraries, and I noticed that most of them take input in this form: [{"foo": "bar", "12": "true"}]
According to json.org:
So we are sending an object in an array.
So I have a two part question:
Part 1:
Why not just send an object or an array, which would seem simpler?
Part2:
What is the best way to create such a Json with Php?
Here is a working method, but I found it a bit ugly as it does not work out of the box with multi-dimensional arrays:
<?php
$object[0] = array("foo" => "bar", 12 => true);
$encoded_object = json_encode($object);
?>
output:
{"1": {"foo": "bar", "12": "true"}}
<?php $encoded = json_encode(array_values($object)); ?>
output:
[{"foo": "bar", "12": "true"}]
Because that's the logical way how to pass multiple objects. It's probably made to facilitate this:
[{"foo" : "bar", "12" : "true"}, {"foo" : "baz", "12" : "false"}]
Use the same logical structure in PHP:
echo json_encode(array(array("foo" => "bar", "12" => "true")));
An array is used as a convenient way to support multiple parameters. The first parameter, in this case, is an object.
Question one:
JSON is just a way of representing an object and/or and array as a string. If you have your array or object as a string, it is much easier to send it around to different places, like to the client's browser. Different languages handle arrays and objects in different ways. So if you had an array in php, for example, you can't send it to the client directly because it is in a format that only php understands. This is why JSON is useful. It is a method of converting an array or object to a string that lots of different languages understand.
Question two:
To output an array of objects like the above, you could do this:
<?php
//create a test array of objects
$testarray = array();
$testarray[] = json_decode('{"type":"apple", "number":4, "price":5}');
$testarray[] = json_decode('{"type":"orange", "number":3, "price":8}');
$testarray[] = json_decode('{"type":"banana", "number":8, "price":3}');
$testarray[] = json_decode('{"type":"coconut", "number":2, "price":9}');
$arraycount = count($testarray);
echo("[");
$i = 1;
foreach($testarray as $object)
{
echo(json_encode($object));
if($i !== $arraycount)
{
echo(",");
}
$i += 1;
}
echo("]");
?>
This will take an array of objects and loop over them. Before we loop over them, we output the opening square bracket.
Then, for each object in the array, we output it encoded to JSON plus a comma after each one. We count the number of iterations so that we don't output a comma at the end.