Iteration using mongoDB and PHP - php

I have a quiz DB which has particular arrangement as shown below:
"question" : "What are the two binary numbers?",
"answers" : {
"ch1" : "1 and 0",
"ch2" : "1 and 2",
"ch3" : "1 to 9"
},
"rightanswer" : "ch1" }
There are n number of such entries in the DB quiz. Now I will have loop through the entire DB and print each value.
how can this can done in for loop; I'm just looking like question[i], answer.ch1[i], answer.ch2[i] .... how to retrieve?
var-dump Results:
array(4) {
["_id"]=> object(MongoId)#7 (1) { ["$id"]=> string(24)"56bb13aef9f36fe751eecfe4" }
["question"]=> string(32) What are the two binary numbers?"
["answers"]=> array(3) {
["ch1"]=> string(7) "1 and 0"
["ch2"]=> string(7) "1 and 2"
["ch3"]=> string(6) "1 to 9"
}
["rightanswer"]=> string(3) "ch1"
}
array(4) {
["_id"]=> object(MongoId)#8 (1) { ["$id"]=> string(24) "56bb1714f9f36fe751eecfe5" }
["question"]=> string(51) "It is a standard specifying a power saving feature?"
["answers"]=> array(3) { .....

I assume you will connect to collection, and in code collectionName is the name of table.
$connection = new MongoClient();
$collection = $connection->database->collectionName;
$cursor = $collection->find();
foreach ( $cursor as $id => $value )
{
echo "$id: ";
var_dump( $value );
//echo $value->question_id;
//echo $value->answers->ch1;
}
You can replace the code and print field name inside the loop the way you want.
Thanks
Amit

Since you managed to print $obj["question"] with expected result, iteration over answers must be:
foreach($obj["answers"] as $key=>$answer) {
echo "$key: $answer"; //or whatever format you need
}

Related

Further data retrieving inside array of JSON using PHP

I have a JSON file I want to fill in a table, but can't quite figure out how to retrieve the data inside and loop it through an array to get in a table I made.
This is my JSON file: test.JSON:
{
"data":{
"Chair":{
"id":24,"key":"Chair","name":"Chair","title":"oak home made"
},
"Table":{
"id":37,"key":"Table","name":"Table","title":"round white table"
},
"Closet":{
"id":18,"key":"Closet","name":"Closet","title":"big and red"
},
"Sofa":{
"id":110,"key":"Sofa","name":"Sofa","title":"room for five persons"
}
},
"type":"furniture","version":"1.1.0"
}
Then with PHP I used this: test.PHP:
$url = 'test.json';
$result=file_get_contents($url);
$decoded=json_decode($result, true);
var_dump($decoded);
This is what I get:
array(3) { ["data"]=> array(4)
{
["Chair"]=> array(4)
{ ["id"]=> int(24) ["key"]=> string(5) "Chair" ["name"]=> string(5) "Chair" ["title"]=> string(13) "oak home made" }
["Table"]=> array(4)
{ ["id"]=> int(37) ["key"]=> string(5) "Table" ["name"]=> string(5) "Table" ["title"]=> string(17) "round white table" }
["Closet"]=> array(4)
{ ["id"]=> int(18) ["key"]=> string(6) "Closet" ["name"]=> string(6) "Closet" ["title"]=> string(11) "big and red" }
["Sofa"]=> array(4)
{ ["id"]=> int(110) ["key"]=> string(4) "Sofa" ["name"]=> string(4) "Sofa" ["title"]=> string(21) "room for five persons" }
}
["type"]=> string(9) "furniture" ["version"]=> string(5) "1.1.0"
}
Then I am trying to retrieve "Chair", "Table", "Closet" and "Sofa", but I don't know how to do it. When I try this:
foreach ($decoded as $key => $value) {
echo "key: ".$key;
echo "</br></br>";
echo "value: ".$value;
echo "</br></br>";
return;
}
I get:
key: data
value: Array
Can someone help me get "Chair", "Table", "Closet" and "Sofa", including each of thoses' id, key, name and title?
I have received guides, but they won't help me because I feel like this type of "array" is different then the links for guides I receive.
Thanks!
You are looping through the array on the top most level, while you want to be a level lower than that to be able to loop through all the elements of data, like this:
foreach ($summonerDecoded2['data'] as $key => $value)
{
echo "key: ".$key."</br>";
echo "value id: ".$value['id']."</br>";
echo "value key: ".$value['key']."</br>";
echo "value name: ".$value['name']."</br>";
echo "value title: ".$value['title']."</br>";
}
You can just do this:
$url = 'test.json';
$result=file_get_contents($url);
$decoded = json_decode($result, true);
foreach ( $decoded["data"] as $key => $value) {
echo $value[ "key" ];
echo "<br />";
//You can access data by:
/*
echo $value[ "id" ];
echo $value[ "key" ];
echo $value[ "name" ];
echo $value[ "title" ];
*/
}
This will result to:
Chair
Table
Closet
Sofa

Query gives one indexed array with many elements

I have code like this:
$ch = #new mysqli ($config['db']['host'],$config['db']['user'],$config['db']['password'],$config['db']['database']);
if($result = $ch->query("SELECT pid FROM posts"))
{
while($pids = $result->fetch_assoc())
{
var_dump($pids);
}
var_dump gives me:
array(1) { ["pid"]=> string(1) "1" } array(1) { ["pid"]=> string(1) "2" } array(1) { ["pid"]=> string(1) "3" } array(1) { ["pid"]=> string(1) "4" }
I have two problems:
In database column 'pid' is an int type but the query yields an array of strings
All records from database (4) are saved in one row in an array (got only one index)
Because of that I can't use max(), because it gives me all records (4321).
You have got 4. Check correctly. The var_dump() executes four times, returning a single array (column - row values):
array(1) {
["pid"]=> string(1) "1"
}
array(1) {
["pid"]=> string(1) "2"
}
array(1) {
["pid"]=> string(1) "3"
}
array(1) {
["pid"]=> string(1) "4"
}
If you want everything to be in a single variable, use:
$allPids = array();
while (false != ($pids = $result->fetch_assoc())) {
$allPids[] = $pids;
}
var_dump($allPids);
You need to store them in one array first.
while($pids = $result->fetch_assoc())
{
$array[] = $pids;
}
var_dump($array);
And for the data type PHP will cast them accordingly.

How to add data to OBJECT from Wordpress get_results in PHP

Seems really easy, but I can't seem to figure it out...
I have a simple line that gets mysql results through wordpress like this:
$sql_results = $wpdb->get_results($sql_phrase);
Then I parse it as JSON and echo it: json_encode($sql_results);
However, I want to add other data before I parse it as JSON. But I'm not sure how.
$sql_results basically gets me a list of post ID's, title and category.
It looks like this in var_dump (this is just the first row):
array(1)
{
[0]=> object(stdClass)#2737 (7)
{
["ID"]=> string(4) "2700"
["post_title"]=> string(18) "The compact helmet"
["category"]=> string(5) "Other"
}
}
Now to start with something easy, I'd like all associative arrays inside the object to have the extra key-value. I tried the following but got an error:
500 Internal error.
foreach($sql_search as $key => $value)
{
$value['pic_img'] = "test";
$sql_search[$key]=$value;
}
$result=$sql_search;
$sql_results = array(1)
{
[0]=> object(stdClass)#2737 (7)
{
["ID"]=> string(4) "2700"
["post_title"]=> string(18) "The compact helmet"
["category"]=> string(5) "Other"
}
}
foreach($sql_results as $key=>$value)
{
$value->solution = 'good';
$sql_results[$key]=$value;
}
$result=$sql_results;
var_dump($result);
$test = array ( array("ID"=>"35", "name"=>"Peter", "age"=>"43"),
array("ID"=>"34", "name"=>"James", "age"=>"19"), array("ID"=>"31", "name"=>"Joe", "age"=>"40") );
foreach($test as $key=>$value)
{
$value['solution'] = 'good';
$test[$key]=$value;
}
$result=$test;
var_dump($result);

convert php array to javascript literal object

I have a php page which returns a php array as the following
array(6) {
[0]=>
array(2) {
["cityName"]=>
string(10) "Ananindeua"
[0]=>
string(10) "Ananindeua"
}
[1]=>
array(2) {
["cityName"]=>
string(8) "An�polis"
[0]=>
string(8) "An�polis"
}
[2]=>
array(2) {
["cityName"]=>
string(8) "Anderson"
[0]=>
string(8) "Anderson"
}
[3]=>
array(2) {
["cityName"]=>
string(6) "Angers"
[0]=>
string(6) "Angers"
}
[4]=>
array(2) {
["cityName"]=>
string(9) "Angoul�me"
[0]=>
string(9) "Angoul�me"
}
[5]=>
array(2) {
["cityName"]=>
string(6) "Anshan"
[0]=>
string(6) "Anshan"
}
}
I want to use this array in another page to do some ajax, and I want to encode the resulat into a JSON as the following :
{
"cityName": "Anshan",
"cityName": "Angoul�me",
"cityName": "Anderson",
"cityName": "An�polis",
"cityName": "Ananindeua"
}
but Instead I get only one value, which is the last value :
{
"cityName": "Anshan"
}
This is the code I tried :
<?php
$connexion = new PDO("mysql:host=localhost;dbname=world", 'root', 'toor');
$statement = $connexion->prepare("SELECT cityName FROM cities WHERE cityName LIKE '" . $_POST['cityName'] . "%'");
$statement->execute();
$resultats = $statement->fetchAll();
foreach($resultats as $city) {
$output[key($city)] = current($city);
}
echo json_encode($output, 128);
?>
So how can I solve this problem ?
Edit :
I tried to get only cities names, and push them into an array, when I do a var_dump() for this array this is what I get :
array(6) {
[0]=>
string(10) "Ananindeua"
[1]=>
string(8) "An�polis"
[2]=>
string(8) "Anderson"
[3]=>
string(6) "Angers"
[4]=>
string(9) "Angoul�me"
[5]=>
string(6) "Anshan"
}
But when I did a json_encode() I don't get anything, so I tried to do a var_dump(json_encode($output)); and I get this :
bool(false)
In the second time I tried to create a table manually :
$a = array("Ananindeua","Anápolis","Anderson","Angers","Angoulême","Anshan" );
and it worked.
But why the first array won't encode !
Your desired output is not valid/conceivable either as a PHP associative array or JSON because in both cases, you have duplicate keys.
You're just overwriting the cityName key with each iteration. Push to an array instead:
foreach($resultats as $city) {
$output[] = current($city);
}
echo json_encode($output, 128);
Output:
[
"Anshan",
"Angoulme",
"Anpolis"
]
Or if you want an object for each city, which is useful if you want other properties:
foreach($resultats as $city) {
$output[] = array(
'cityName' => current($city)
);
}
echo json_encode($output, 128);
Output:
[
{
"cityName" : "Anshan",
},
{
"cityName" : "Angoulme",
},
{
"cityName" : "Anpolis"
}
]
Side note: if you don't need the numerical keys from the PDO fetch call, consider using the PDO::FETCH_ASSOC fetch style, to bring back only associative keys:
$resultats = $statement->fetchAll(PDO::FETCH_ASSOC);
The json you're expecting doesn't look right. It should be:
[
{"cityName": "Anshan"},
{"cityName": "Angoul�me"},
{"cityName": "Anderson"},
{"cityName": "An�polis"},
{"cityName": "Ananindeua"}
]
and to generate this you need code like this:
foreach($resultats as $city) {
$item = new stdClass();
$item.cityName = current($city);
$output[] = item;
}
Your array's key is same (cityName), so the value getting replaced on each assignment.
use a numeric array, or another method that differentiating the key
e.g.,
foreach($resultats as $city) {
$output['cityName'][] = current($city);
}
output will be
{"cityName":
[
"Anshan",
"Angoulme",
"Anpolis"
]
}
The problem was that the table which I populate from database contains some accented characters, so the json_encode() failing.
The solution was to add charset=UTF8 in the first parameter of the PDO instance.
$connexion = new PDO("mysql:host=localhost;dbname=world;charset=UTF8", 'root', 'toor');

I have two values in an array when i execute the stored Procedure in php But iam returned wih one array value

$result = $mysql->callSP('STOREDPE1',$in);
$arr_tmp=array();
foreach ($result['record'] as $rows) {
echo "one value";
if(!empty($rows)){
echo "Two Value";
$arr_tmp[$rows['field1']] = $rows['field2'];
}
}
return $arr_tmp;
When I say var_dump($result) it has two values in array. But when I Execute arr_tmp it is returned with one value.
out put of ``var_dump($result)`
["param"]=>
array(4) {
["whcode"]=>
string(5) "001"
["mode"]=>
string(1) "A"
["stock_type"]=>
string(4) "AAA"
["process_name"]=>
string(7) "AAAA"
}
["record"]=>
array(2) {
[0]=>
array(3) {
["Field1"]=>
string(5) "value1"
["Field2"]=>
string(1) "CCC"
["Field3"]=>
string(4) "BCC"
}
[1]=>
[0]=>
array(3) {
["Field1"]=>
string(5) "value1"
["Field2"]=>
string(1) "CCC"
["Field3"]=>
string(4) "BCC"
}
}
}
output of var_dump (arr_tmp)
[1]=>
[0]=>
array(3) {
["Field1"]=>
string(5) "value1"
["Field2"]=>
string(1) "CCC"
["Field3"]=>
string(4) "BCC"
}
Both the array values seems to be same
I have the values overwriting in the array
Very hard to understand and read with the bad formatting, please take care to post it with proper formatting.
I think the answer is this:
$result = $mysql->callSP('STOREDPE1',$in);
$arr_tmp=array();
foreach ($result['record'] as $rows) {
echo "one value";
if(!empty($rows)){
echo "Two Value";
$arr_tmp[][$rows['field1']] = $rows['field2'];
}
}
var_dump($arr_tmp);
That should store both sets of data, you just needed to make it a multi-dimensional array. That is, if that is your question and I did not mis-read it through that garbled text above.
Update
This option is not recommended better to learn how to use arrays, simply posted for an example of usage:
$result = $mysql->callSP('STOREDPE1',$in);
$arr_tmp=array();
$i=0;
foreach ($result['record'] as $rows) {
echo "one value";
if(!empty($rows)){
echo "Two Value";
$arr_tmp[][$rows['field1'] . "_$i"] = $rows['field2'];
}
$i++;
}
var_dump($arr_tmp);

Categories