Encoding Json from MySQL - php

So I am trying to encode to JSON from MySQL and I need it in a [pagenumber][id,type,description][answerid,answerdescription] format. The goal of this is to read the data in a javascript file that will generate a multi step poll for me.
I will try to draw a pseudocode on how I want it to look right here:
{"pages":
[{1:
[{"id":1,"text":"U mad?","options":
[{"opt_id":1,"option":"yes","answer:''"},
{"opt_id":2,"option":"no","answer:''"},
{"opt_id":3,"option":"perhaps","answer:''"}]},
{"id":2,"text":"Got it?","options":
[{"opt_id":1,"option":"yes","answer:''"},
{"opt_id":2,"option":"no","answer:''"}]
}]
},
{2:
[{"id":3,"text":"Help me?","options":
[{"opt_id":1,"option":"yes","answer:''"},
{"opt_id":2,"option":"no","answer:''"},
{"opt_id":3,"option":"perhaps","answer:''"}]},
{"id":4,"text":"Please?","options":
[{"opt_id":1,"option":"yes","answer:''"},
{"opt_id":2,"option":"no","answer:''"}]
}]
}]
}
This is what I got so far, but I can't seem to think of a way to add the 3rd "dimension" to this, I want an array of [id => (int), description => (string)] attached to each question. And each question needs room for several answers connected to them. The last column in the answers/options array is for text strings (most answers are answered by ID numbers, but some are textareas that needs whole strings). this might not be needed as I can probably send the form results back by serializing.
$rows = array();
while($r = mysql_fetch_assoc($sth))
{
$Qid = $r['id'];
$page=$r['page'];
$type=$r['type'];
$Qdesc=$r['description'];
$rows[$page][] = array(
'id' => $Qid,
'type' => $type,
'description' => $Qdesc);
}
The result of this is the following (first 3 pages).
{
"1":[
{"id":"2","type":"1","description":"U mad?"},
{"id":"3","type":"1","description":"Got it?"},
{"id":"4","type":"1","description":"Help me?"}],
"2":[
{"id":"5","type":"1","description":"Please?"},
{"id":"6","type":"1","description":"Any clues?"}],
"3":[
{"id":"7","type":"2","description":"Foobar?"}]}

How about an options table?
id, option, answer
1, yes, ''
2, no, ''
3, perhaps, ''
(your answer data is always empty so I've included it for consistency)
Then for each question you would have an options field with "1,2,3" for all the options "1,2" for just yes/no etc..
To implement this you could:-
$options=array();
if(!empty($r['options']))
{
$sql="SELECT * FROM options_table WHERE id IN (".$r['options'].")";
$result=mysql_query($sql);
while($row=mysql_fetch_assoc($result){
$options[]=$row;
}
}
$rows[$page][] = array(
'id' => $Qid,
'type' => $type,
'description' => $Qdesc,
'options'=>$options);
This way you could add options to your hearts content

This is not an entire answer, but to help you start off, you could have:
json_encode(array("pages" => array(1 => $row1, 2=>$row2)));
Generally you can achieve multilevel nesting using array(..) within another array(..). Like:
json_encode(
array(
$item1,
$item2,
array(
"key1" => array(
1,
2,
array(
"inKey1" => array(4,5,6)
)
)
)
)
);

Related

How to use if for this array

I want to use if for this array :
$options[] = array( "name" => __('slider Settings','wordpresstools'),
"desc" => __('','wordpresstools'),
"id" => $shortname."_favSlider",
"std" => "",
"type" => "select",
"options" => array(
'option1' => 'test',
'option2' => 'test 2',
'option3' => 'test 3'
));
if this select option = option1
echo " Test ";
I have more $options , but I want to if just for that option ( Slider Settings )
Thanks .
Maybe the problem in your code are those brackets after $options. That way you append a new array element to the collection which means you have to test for something like this:
// Assuming your code creates the first array element
if ($options[0]['std'] == 'option1') {
// Do your stuff
}
If you don't need the square brackets in your first line of code it would look like this:
$options = array(/* Your values */);
if ($options['std'] == 'option1') {
// Do your stuff
}
$shortname='test';
$options = array( "name" => create_function('slider Settings','wordpresstools'),
"desc" => create_function('','wordpresstools'),
"id" => $shortname."_favSlider",
"std" => " I am here",
"type" => "select",
"options" => array(
'option1' => 'test',
'option2' => 'test 2',
'option3' => 'test 3'
));
echo "<pre>";
print_r($options['std']);
If i am right you try to create a constructor function there. In order to do something like that you must use create function. Read more details here The output of this code is printing std field as you want. The downside is that this method will be deprecated in PHP 7.2 so maybe you can find another work around than creating functions inside an array.
Foreach loop on options
foreach($options['options'] as $k=>$v){
// Check value of key
if($k == 'option1'){
echo $v . "\n";
}
}
I'm not exactly sure what kind of implementation you need but this should be a decent start for however you're trying to use it. I'm not sure if you mean to always have option1, option2, option3, etc. set or if you're checking to see if they exist. If the prior, then you'd need to make a few slight changes; if the latter, then this should work fine as it will check every key value and it should only exist if the option is selected.

Simpliest way to build a multi-dimensional array with SQL result?

I am currently building a web planning and I want to show some data in the period display.
I have a PHP file where I create my SQL request over ~13 tables and fetch all results (I use PDO::FETCH_ASSOC), then I have to loop over my result to build the array I want.
The problem is I need to build a complicated array with lot of data. Here is the kind of result I want to achieve :
$result = array(
$place_1 => array(
'data_place' => array(
'id' => ...,
'name' => ...,
// etc.
),
'data_target' => array(
$target_type_1 => array(
$name_1 => ...,
$name_2 => ...,
// etc.
),
$target_type_2 => array ( ... ),
// etc.
),
'data_isOpen' => array(
$day_1 => array(
$hour_begin => ...,
$hour_end => ...
),
$day_2 => array ( ... ),
// etc.
),
'data_box' => array(
// same kind of stuff with more dimension
)
),
...
$place_n = array(
// same
)
);
When I execute my request, I get something like 3000 array with all the data I need, but I only have 29 places in database so there is a lot of repetition...
$result = array(
0 => array(
"id" => ...,
"name" => ...,
// the list of all fields I need in my big array
),
...
n => array(
// same
)
);
I almost manage to achieve the result I want with some "foreach" and headaches but here is my question :
Is it possible to build a SQL request and fetch the result as I want? I mean, can I group all the result by "id_place" for example but wihtout lost information? And if it's possible, can we do it multiple time?
The idea is to get a result with one array for every place (so 29 and not 3000), then for every "place array", group for example the "hour_begin" and "hour_end" by "opening_day", etc...
Sorry if it's a duplicate, I didn't saw any positive anwser to my question so I try again !

PHP - Format string

I have problems when trying to print on screen this string:
[(E/X)^x]^2
I'm not able to render it correctly here too, but (E/X) should be elevated to x, and then everything to 2.
I hope I was clear.
Thanks!
EDIT
I try to explain myself better. I have $colHeaders, which is an array of array used to give data to a table. In the second child array, title field, is the string I want to render as I asked in the question.
The string must be formatted.
$colHeaders = array(
array(
'title' => $this->translator->trans('price'),
'rowspan' => 2,
'colspan' => 0
),
array(
'title' => '[(E/X)^x]^ 2',
'rowspan' => 0,
'colspan' => 2
),
);
You don't need PHP, it's a simple HTML formatting using the tag. Basically the output you want is:
[(E/X)<sup>x</sup>]<sup>2</sup>
In PHP, you just need to echo that, as such:
echo '[(E/X)<sup>x</sup>]<sup>2</sup>';

How can I determine the current php array number

Good Afternoon.
I'm attempting to make an array list with one of the key values being ($_REQUEST['qty#']), where "#" would be the current number of the item within the array (as it pertains to a field in a form that gathers this info).
For example:
$itemdetails = array(
array(
'qty' => ($_REQUEST['qty1']),
'price' => 0.70,
'pn' => 'TV-1000',
array(
'qty' => ($_REQUEST['qty2']),
'price' => 0.99,
'pn' => 'TV-5000'));
Is there any way that I can automatically have the number in ($_REQUEST['qty']) be determined without having to type in the numbers manually?
Just wondering. My next guess would be to enter it all into a database and pull it from there.
Thanks a bunch in advance.
You would need to loop ...
$itemdetails = array(
array(
'price' => 0.70,
'pn' => 'TV-1000'
),
array(
'price' => 0.99,
'pn' => 'TV-5000'
)
);
foreach ( $itemdetails as $k => &$item ) {
$item['qty'] = $k + 1;
}
What you should do is pass an array of data via POST/GET.
To do this in your inputs, you make the name value = qty[] for each input. Note the array syntax [] here.
PHP will automatically take all values for input with that array syntax and build an array out of it in $_POST/$_REQUEST.
So you would be able to access your array like
var_dump($_POST['qty']);
var_dump($_REQUEST['qty']);
That however still doesn't give the ability to match this to the price/pn as you need. So, let's take the array syntax one step further and actually put a key value in it like this:
<input name="qty[0]" ... />
<input name="qty[1]" ... />
By doing this you will be able to know exactly which array index matches which item (assuming you know the order the inputs were displayed in).
The would make $_POST['qty'][0] be the first item, $_POST['qty'][1] be the next and so on.
So assuming you also have you prices/pn in an array like this:
$item_array = array(
0 => array('price' => 123, 'pn' = 'ABC'),
1 => array('price' => 456, 'pn' = 'XYZ'),
...
);
You could then easily loop through the input quantities and build you final array like this:
$itemdetails = array();
foreach ($_REQUEST['qty'] as $key => $value) {
$itemdetails[$key] = $item_array[$key];
$itemdetails[$key]['qty'] = $value;
)
Also note, that if you are expecting this data to be passed via POST, it is considered best practice to use the $_POST superglobal rather than the $_REQUEST superglobal.

problem with array and GoogChart

ok.. I know I can find help here :)
I am barely out of noobhood so be gentle :)
I'm trying to fetch data from a db and use it to call a pie chart in GoogChart so here is my problem... some code like db connections etc. is skipped to get to the point.
First we look at the array GoogChart uses to pass the info:
$data = array(
'8' => 6,
'3' => 3,
'9' => 2,
);
Now we look at how I am trying to do it pulling the data from a db:
//connect and query here
while ($row=mysql_fetch_array($query)){
$viewid=trim($row['id']);
$total_views=trim($row['views']);
// trimmed cuz I can't sort it out
$dat = "'$viewid' => $total_views,"; //problem likely here
}
$data = array(
$dat
);
When I echo the $dat, I get this:
'8' => 6,'3' => 3,'9' => 2,
So theoretically, it should work??? But noop :(
There may be a totally different way of doing this but I'm stumped... didn't take much to do it either lol.
What you're doing is creating an array with one element: "'8' => 6,'3' => 3,'9' => 2,".
Instead, you should be populating an array as you go:
$data = array(); // create the array
while ($row=mysql_fetch_array($query)){
$viewid=trim($row['id']);
$total_views=trim($row['views']);
// use the $viewid as the key and $total_views as the value
$data[ $viewid ] = $total_views;
}
Of course, you could also do (not certain if this could help you, but it is an option):
$data = array(); // create the array
while ($row=mysql_fetch_array($query)){
// use the $viewid as the key and $total_views as the value
$data[ trim($row['id']) ] = trim($row['views']);
}

Categories