output error in php json-decode - php

my php code generate a non-Valid json output error
my php code :
$questions = array();
while($question = mysql_fetch_array($result, MYSQL_ASSOC)) {
$questions[] = array('question'=> $question);
}
print_r ($questions);
$newQuestions = array('questions' => array());
foreach($questions as $key => $question){
$newQuestion = array(
'question' => $question['question']['question'],
'correct' => $question['question']['correct'],
'answers' => array(
$question['question']['answer1'],
$question['question']['answer2'],
$question['question']['answer3'],
$question['question']['answer4']
)
);
$newQuestions['questions'][] = $newQuestion;
}
$output = json_encode(($newQuestions),JSON_UNESCAPED_UNICODE);
echo '<br/><br/>';
echo $output;
table fields :
Question :
correct :
answer 1 :
answer 2 :
answer 3 :
answer 4 :
Example :
Question : is php a good language ?
correct : 1
answer 1 : yes
answer 2 : no
answer 3 : maybe
answer 4 : good
the output is OK, and formated as I want.
output sample : http://pastebin.com/eefS7KYW
I am sure my php code is correct but I don't know where is exactly the issue !!
==============
Fixed : it was just two echo $output !

Seems like you are doing a lot of variable passing which gets very confusing, very quickly. Especially when all the variables are iterations of 'question'. It appears that you are creating an array from information pulled from a database in the format [questions[question,correct,answers[1,2,3,4]]] This code format may work better?
$newQuestions = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$newQuestions['questions'][] = array(
'question' => $row['question'],
'correct' => $row['correct'],
'answers' => array(
$row['answer1'],
$row['answer2'],
$row['answer3'],
$row['answer4']
)
);
}
$output = json_encode(($newQuestions),JSON_UNESCAPED_UNICODE);
echo '<br/><br/>';
echo $output;
Had a semicolon in the wrong place.Fixed the code above and test the code with the following:
<?php
$array = array(
array('question'=>'Question1',
'correct'=>3,
'answer1' => 'Q1Answer1',
'answer2' => 'Q1Answer2',
'answer3' => 'Q1Answer3',
'answer4' => 'Q1Answer4'
),
array('question'=>'Question2',
'correct'=>3,
'answer1' => 'Q2Answer1',
'answer2' => 'Q2Answer2',
'answer3' => 'Q2Answer3',
'answer4' => 'Q1Answer4'
),
array('question'=>'Question3',
'correct'=>3,
'answer1' => 'Q3Answer1',
'answer2' => 'Q3Answer2',
'answer3' => 'Q3Answer3',
'answer4' => 'Q1Answer4'
)
);
$newQuestions = array();
//while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach($array as $row){
$newQuestions['questions'][] = array(
'question' => $row['question'],
'correct' => $row['correct'],
'answers' => array(
$row['answer1'],
$row['answer2'],
$row['answer3'],
$row['answer4']
)
);
}
print_r($newQuestions);
$output = json_encode(($newQuestions),JSON_UNESCAPED_UNICODE);
echo '<br/><br/>';
echo $output;
?>

Related

assign array data in PHP

I did search for this but may be my search sucks. So posting it here..my code below
while( $row = mysqli_fetch_array($queryRecords) ) {
$data['data'][] = array(
'student_name' => $row['name'],
'totalmark' => $row['totalmark'],
$marksheet = calculatepercent(totalmark),
'resultdate' => $row['resultdate'].$marksheet,
'ID' => $row['ID']
);
Here I call function calculatepercent(totalmark) so that the function returns a value and store that in $marksheet. But my problem is this does not work i.e I cannot store the result of calculatepercent(totalmark) because I cannot access 'totalmark'
Forget performance for a minute but how do you make this work? (If you have tips for performance that's a bonus too! ) - Thanks Coders!
RR
Try like this.Send $row['totalmark'] to the calculatepercent() function.
while( $row = mysqli_fetch_array($queryRecords) ) {
$data['data'][] = array(
'student_name' => $row['name'],
'totalmark' => $row['totalmark'],
$marksheet => calculatepercent($row['totalmark']),
'resultdate' => $row['resultdate'].$marksheet,
'ID' => $row['ID']
);
I guess I was more desperate than any one else to get an answer! So after trying many things I got it working and sharing it here for any one else
while( $row = mysqli_fetch_array($queryRecords) ) {
$marksheet = calculatepercent($row['totalmark'];
$data['data'][] = array(
'student_name' => $row['name'],
'totalmark' => $row['totalmark'],
//move the fn 'calculatepercent' outside while loop $marksheet => //calculatepercent($row['totalmark']),
'resultdate' => $row['resultdate'].$marksheet,
'ID' => $row['ID']
);

How can I create a specific JSON string?

I want to create this JSON string with PHP:
[{name:'20140722.1304',data:[[0, 0.224],[0, 0.228]] }, {name:'20140729.1149',data:[[1, 0.224],[1,0.228]] }]
My current attempt:
$jsonArray = array(
'name' => '20140722.1304'
,'data' => array('0' => '0.024', '1'=> '0.028')
);
$jsonValue = json_encode($jsonArray);
echo $jsonValue;
But this code's output looks like:
{"name":"20140722.1304","data":["0.024","0.028"]}
Where did I went wrong? What do I have to change in my code to get to my expected output?
I finally got you to tell us what you want in the comments; please be up-front with this in the future. The expected output you gave differed from your actual output in so many ways that it was impossible to tell what you actually thought the problem was, but:
I want to get the output as {name:'20140722.1304',data:[[0, 0.224],[0, 0.228]]}
At this point, the only difference I can see is that your data is a nested array in your expected output, but not your actual output.
That has nothing to do with JSON. You're just not building your input array correctly.
Try json-encoding this:
$jsonArray = array(
'name' => '20140722.1304'
,'data' => array(array(0, 0.024), array(0, 0.028))
);
<?php
for($i=0;$i<2;$i++)
{
$jsonArray[] = array(
'name' => '20140722.1304'
,'data' => array('0' => '0.024', '1'=> '0.028')
);
}
//$jsonValue = json_encode($jsonArray);
$jsonValue = json_encode($jsonArray,true);
echo$jsonValue;
?>
try this
$jsonArray = array(
'name' => '20140722.1304'
,'data' => array('0' => '0.024', '1'=> '0.028')
);
$out = array_values($jsonArray);
echo json_encode($out);
output:
["20140722.1304",["0.024","0.028"]]
EDit:
$array = array(
2 => array("name" => '20140722.1304'),
4 => array("'data" => array('0' => '0.024', '1'=> '0.028')));
$out = array_values($array);
echo json_encode($out);
output:
[{"name":"20140722.1304"},{"'data":["0.024","0.028"]}]

Codeigniter combining information

first of, just wanted to let you know that I am a newbie at CI. but I am having trouble with this piece of code where is breaking and I can't seem to be able to find the answer anywhere.
for some reason the code is breaking at the first if statement.. if possible could you help me out understand what is really happening there?
Thank you all for your help!
function main
{
$this->load->model(getData) psudo code for this area...
}
---model---
function getData....
{
Sql = this->db->query(sql code that returns all the information required.)
$result = $sql->result_array();
$types = array ( 'EVENT|TIME' => array( 'id' => 1, 'name' => 'Regular' ),
'PROPOSITION|REGULAR' => array( 'id' => 2, 'name' =>'Propositions'),
'EVENT|TIME' => array( 'id' => 3, 'name' => 'Now' ),
'PROPOSITION|FUTURES' => array( 'id' => 4, 'name' => 'Future' ));
$var = array();
foreach ($result as $event) {
$cat = $event['type'] . '|' . $event['sub_type'];
$typeId = $types[$cat]['id'];
if(!is_array($var[$event['event_id']]['var'][$event['type_id']]))
{
if(!is_array($var[$event['event_id']]))
{
$var[$event['event_id']] = array( 'event_name' =>
$event['event_name'],'event_abbreviation' =>
$event['event_abbreviation']);
}
$var[$event['event_id']]['var'][$event['type_id']] = array(
'type_name' => $event['abbreviation'],'type_abbreviation' => $event['name']
);
}
$event[$event['event_id']]['var'][$event['type_id']]['types'][$typeId] =
$types[$cat]['name'];
}
return $myResults;
}
In this line
if(!is_array($var[$event['event_id']]['var']$event['type_id']]))
You are missing a [ somewhere. I'm guessing before $event['type_id'].
So replace with:
if(!is_array($var[$event['event_id']]['var'][$event['type_id']]))

Multidimensional array in php to save mysqli output

Here is a piece of my code:
if($all_pages)
foreach ($all_pages as $page)
{
$all_hokms = $mysqli->query("SELECT * FROM qm_hokm WHERE page_id = ".$page['page_id']."");
if($all_hokms)
foreach ($all_hokms as $hokm)
{
$one_page_ahkams[] = array(
'hokm_id_inPage' => $hokm['hokm_id_inPage'],
'type' => $page['type'],
);
}
else
$one_page_ahkams[] = array();
$all_pages_data[] = array(
'page_id' => $page['page_id'],
'done' => $page['done'],
'checked' => $page['checked'],
'ahkams' => array($one_page_ahkams), //Here Is the PROBLEM : (((
);
}
else
$all_pages_data[] = array();
echo json_encode($all_pages_data);
As you see, I want to send multidimensial array() in a json format (from server to client), but how can correct the insertion of an array in an other, I mean that I need to add $one_page_ahkams array in $all_pages_data one, any ideas
$one_page_ahkams = array();
$all_pages_data[] = array(
'page_id' => $page['page_id'],
'done' => $page['done'],
'checked' => $page['checked'],
'ahkams' => array($one_page_ahkams);//this comma (,) causes the problem i guess**
);
An other way to do it :
$all_pages_data[] = array(
'page_id' => $page['page_id'],
'done' => $page['done'],
'checked' => $page['checked'],
'ahkams' => array(['one_page_ahkams']=>$one_page_ahkams);
);
Just put that: 'ahkams' => array($one_page_ahkams), but check the content of $one_page_ahkams

Php foreach loop without to override variables

I have difficult times to figure out how to manage my loop to not override variables during the process, my example script looks as it follows
$targets = array(
array(
'site_id' => 1,
'url' => array('http://example.com','http://test.com'),
'title' => "Title_1",
'int_link' => "/internal_link/",
'icon' => '/icon_2.gif',
'teaser_index' => 5),
array(
'site_id' => 2,
'url' => array('http://example2.com','http://test2.com'),
'title' => "Title_2",
'int_link' => "/internal_link/",
'icon' => '/icon_2.gif',
'teaser_index' => 5)
)
foreach($targets as $target){
$images = array();
$links = array();
$name = array();
$loop=-1;
foreach($target['url'] as $url){
$loop++;
//parsing $url;
//the insider loop has 2 iterations
if ($loop=1){
$content .="<div>".$target['title'].$url"</div>";
}
else{
$content .="<div>".$target['title'].$url"</div>";
}
}
//write $content html to database, without to override the first $content
}
Your question is not clear but i think i understand what the likely problem might be
There are so many errors in the script which you need to fix maybe your script would run the way you want it to be .
A. $content was not define .. you need to define it
B. if ($loop=1){ should be if ($loop == 1){
C. $content .="<div>".$target['title'].$url"</div>"; is missing . and it should be something like this $content .= "<div>" . $target['title'] . $url . "</div>";
D. You if condition does not make sense since you are outputting the same information
Form what i can see you want to output Title & URL you can as well just use this simple script (Just Guessing)
$targets = array(
array(
'site_id' => 1,
'url' => array('http://example.com','http://test.com'),
'title' => "Title_1",
'int_link' => "/internal_link/",
'icon' => '/icon_2.gif',
'teaser_index' => 5),
array(
'site_id' => 2,
'url' => array('http://example2.com','http://test2.com'),
'title' => "Title_2",
'int_link' => "/internal_link/",
'icon' => '/icon_2.gif',
'teaser_index' => 5)
);
foreach ( $targets as $target ) {
$content = "";
$output = "<div> %s : %s </div>";
$content .= sprintf($output, $target['title'], implode(" , ",$target['url']));
echo $content;
// write $content html to database, without to override the first $content
}
Output
Title_1 : http://example.com , http://test.com
Title_2 : http://example2.com , http://test2.com

Categories