I have a PHP MySQL fetch while loop as shown below in my script:
$result2211 = mysql_query("select * from products where is_config = 'yes' ");
while($row2211 = mysql_fetch_assoc($result2211))
{
$sn = $row2211['sn'];
$allparrentselectq = mysql_query("SELECT * FROM parrentpro where parrentsn = $sn");
while($allparrentselect = mysql_fetch_assoc($allparrentselectq))
{
$childarr = unserialize($allparrentselect['childsn']);
$subpro = '{"catname":"'.$allparrentselect['childname'].'",';
$i = 0;
foreach($childarr as $childarr):
$subpro .= '"Pro'.$i++.'":"'.$childarr.'",';
endforeach;
$subpro1[] = substr($subpro, 0, -1)."}";
$subproa = "[".implode(",",$subpro1)."]";
}
$prodObj2 = new ProductDetails();
$prodObj2->productname = $row2211['productname'];
$prodObj2->price = $row2211['productprice'];
$prodObj2->discount = $row2211['discount'];
$prodObj2->discountprice = $row2211['discountprice'];
$prodObj2->imageURL = $row2211['productimageurl'];
$prodObj2->category = $row2211['productcat'];
$prodObj2->configurablepone = $subproa;
$prodObj2->configurable = 'yes';
array_push($totArr, $prodObj2);
}
In that I have a problem. I get the result as like below (JSON):
[
{
"productname":"Veg.Pizaa",
"price":"350",
"discount":"",
"discountprice":"350",
"imageURL":"http:\/\/farm8.staticflickr.com\/7154\/6694188161_9ee692d854_s.jpg",
"category":"Pizaa",
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"}],
"configurable":"yes"
},
{
"productname":"Core i7 Pc",
"price":"48000",
"discount":"2",
"discountprice":"47040",
"imageURL":"http:\/\/www.4to40.com\/images\/science\/Basic_Computer_Parts\/Computer.jpg",
"category":"Pc",
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},{"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"},{"catname":"Harddisk","Pro0":"Segate 500Gb","Pro1":"Samsung 250Gb"},{"catname":"Ram","Pro0":"8Gb Ram","Pro1":"4Gb Ram","Pro2":"2Gb Ram"}],
"configurable":"yes"
}
]
But I need the result as like below:
[
{
"productname":"Veg.Pizaa",
"price":"350",
"discount":"",
"discountprice":"350",
"imageURL":"http:\/\/farm8.staticflickr.com\/7154\/6694188161_9ee692d854_s.jpg",
"category":"Pizaa",
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"}],
"configurable":"yes"
},
{
"productname":"Core i7 Pc",
"price":"48000",
"discount":"2",
"discountprice":"47040",
"imageURL":"http:\/\/www.4to40.com\/images\/science\/Basic_Computer_Parts\/Computer.jpg",
"category":"Pc",
"configurablepone":[{"catname":"Harddisk","Pro0":"Segate 500Gb","Pro1":"Samsung 250Gb"},{"catname":"Ram","Pro0":"8Gb Ram","Pro1":"4Gb Ram","Pro2":"2Gb Ram"}],
"configurable":"yes"
}
]
As you can see configurablepone JSON is getting repeated for every loop so I am getting the value of the first product in second product also but I need to seperate like below:
First Product As Like Below
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},{"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"}]
Second Product As Like Below
"configurablepone":[{"catname":"Harddisk","Pro0":"Segate 500Gb","Pro1":"Samsung 250Gb"},{"catname":"Ram","Pro0":"8Gb Ram","Pro1":"4Gb Ram","Pro2":"2Gb Ram"}]
I have tried changing the loop but I haven't found any solutions. Kindly help me to solve this.
I think, your problem in line $subpro1[] = substr($subpro, 0, -1)."}";.
So, first call of this line save data from "Veg.Pizaa" into $subpro1[0].
Second call of this line save data from "Core i7 Pc" into $subpro1[1].
Then, line $subproa = "[".implode(",",$subpro1)."]"; merged all array elements.
Just Use unset($subpro1); after the array_push($totArr, $prodObj2);.
Below Is An example Source
Try This One This May Work
$result2211 = mysql_query("select * from products where is_config = 'yes' ");
while($row2211 = mysql_fetch_assoc($result2211))
{
$sn = $row2211['sn'];
$allparrentselectq = mysql_query("SELECT * FROM parrentpro where parrentsn = $sn");
while($allparrentselect = mysql_fetch_assoc($allparrentselectq))
{
$childarr = unserialize($allparrentselect['childsn']);
$subpro = '{"catname":"'.$allparrentselect['childname'].'",';
$i = 0;
foreach($childarr as $childarr):
$subpro .= '"Pro'.$i++.'":"'.$childarr.'",';
endforeach;
$subpro1[] = substr($subpro, 0, -1)."}";
$subproa = "[".implode(",",$subpro1)."]";
}
$prodObj2 = new ProductDetails();
$prodObj2->productname = $row2211['productname'];
$prodObj2->price = $row2211['productprice'];
$prodObj2->discount = $row2211['discount'];
$prodObj2->discountprice = $row2211['discountprice'];
$prodObj2->imageURL = $row2211['productimageurl'];
$prodObj2->category = $row2211['productcat'];
$prodObj2->configurablepone = $subproa;
$prodObj2->configurable = 'yes';
array_push($totArr, $prodObj2);
unset($subpro1);
}
while($allparrentselect = mysql_fetch_assoc($allparrentselectq))
{
$childarr = unserialize($allparrentselect['childsn']);
$subpro = '{"catname":"'.$allparrentselect['childname'].'",';
$i = 0;
foreach($childarr as $childarr):
$subpro .= '"Pro'.$i++.'":"'.$childarr.'",';
endforeach;
$subpro1[] = substr($subpro, 0, -1)."}";
$subproa = "[".implode(",",$subpro1)."]";
$subpro1 = array();
}
try this in second while loop
Related
Hi i am iterating over Episodes getting array of authors and inside this loop i want to gather information about each author. But there is problem, i just need the information about each author once.
This is my approatch, but wrong. and the code i am trying to make. Please help. I tried also in_array, and array_filter but without success.
$presentUsers = [];
$pUi = 0;
if ($isAuthor == true){
if ($project->getType() == 1) {
$episodes = $project->getComic()->getComicEpisodes();
foreach ($episodes as $comicEpisode) {
foreach ($comicEpisode->getProject()->getAccount() as $author) {
if ($author->getUser()->getId() == $this->getUser()->getId()) {
$comicEpisode->setIsMine(true);
$comicEpisode->setRevenue($author->getRevenue());
$comicEpisode->setIncome($author->getIncome());
}
if (empty($presentUsers)){
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}else{
if (!in_array($presentUsers, ['Id'=>$author->getUser()->getId()]))
{
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}
}
}
}
}
}else{
die('You are not the author of this project.');
}
Okay i done it like this
if (empty($presentUsers)){
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}else{
$found = 0;
foreach ($presentUsers as $presentUser){
if ($presentUser['Id'] == $author->getUser()->getId()){
$found = 1;
break;
}
}
if ($found != 1)
{
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}
}
I am trying to display all records using jason in php.
but display all filed with null value.
I'm using postman for testing purpose.
I don't know what is the problem with that code. I getting null value only.
here is my code :
<?php
header('Content-Type: application/json');
$checkFields = "";
$REQUEST = $_SERVER['REQUEST_METHOD'];
if ($REQUEST == "POST")
{
include "DB/db.php";
$userlist = mysql_query("SELECT * FROM reg_services");
if(mysql_num_rows($userlist) > 0)
{
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
$json = array("success" => 1, "All_User_List" => $ph);
$jsonarray = json_encode($json);
}
}
else
{
$json = array("success" => 0, "message" => "Invalid Request Type(Use POST Method)");
$jsonarray = json_encode($json);
}
echo $jsonarray;
?>
please help me if you are know what is the error in code.
just replace this code with old one
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_array($userlist))
{
$ph[$p] = array();
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
You need to tell PHP about arrays
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p] = array(); // let PHP know it is an array
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
just replace this while loop condition with olde one.
while($userlistdata = mysql_fetch_array($userlist))
now it's work
I have a query which I want the results inserted in an array so after all I'll encode it into a JSON, but my problem is that I want the data to be set like this:
array[0] = project1, project2, project3;
array[1] = item1, item2, item3;
and I'm having this:
array[0] = project1;
array[1] = project2;
array[2] = project3;
and so on..
this is what I've done so far:
$info = array();
$items = mysql_query("SELECT * FROM `vision`.`projects` WHERE proj_area = 'area_1'");
if (mysql_num_rows($items) != 0) {
while($proj = mysql_fetch_array($items)) {
$proj_name = $proj['proj_name'];
$proj_beg = $proj['proj_beg'];
$proj_end = $proj['proj_end'];
array_push($info, $proj_name, $proj_beg, $proj_end );
}
}
echo json_encode($info);
my query result gave me these result:
["nome", "0000-00-00", "0000-00-00", "Projeto 2", "2016-12-12", "2020-07-30", "Projeto", "2017-02-03", "2018-03-10"]
and this is my $.getJSON code:
$.getJSON("includes/get_area.php",function(data){
console.log(data);
})
What am I doing wrong?
Try this one; this will add a list in each one of the three array indexes.
$info = array();
$items = mysql_query("SELECT * FROM `vision`.`projects` WHERE proj_area = 'area_1'");
if (mysql_num_rows($items) != 0) {
while($proj = mysql_fetch_array($items)) {
$info[0][] = $proj['proj_name'];
$info[1][] = $proj['proj_beg'];
$info[2][] = $proj['proj_end'];
}
}
echo json_encode($info);
I am using the following PHP code to fetch some data from my database. It contains chats and messages between users in those chats. I want to return the information of both users plus the messages they exchanged. My test data has two chats with ID's 1 and 2. There are two messages, both in chat 1, however for some reason they are returned for both chats 1 and 2. I'm not sure what the problem in my code is.
$response = array();
$myArray = array();
while($row = $user_chats->fetch_array())
{
$myArray["chatId"] = $row["chat_id"];
$myArray["user1_id"] = $row["user1"];
$myArray["user2_id"] = $row["user2"];
$myArray["user1_name"] = $user1_name;
$myArray["user2_name"] = $user2_name;
$myArray["user1_profile_pic"] = $result_user1["profile_pic"];
$myArray["user2_profile_pic"] = $result_user2["profile_pic"];
$messages = array();
$chat_idd = $row["chat_id"];
$chat_messages = mysqli_query($conn,"SELECT * FROM messages WHERE chatID = '$chat_idd' ORDER BY timestamp ASC");
$count = 1;
while($roww = $chat_messages->fetch_array()) {
if ($row["chat_id"] == $roww["chatID"]) {
$messages["message_id"] = $roww["message_id"];
$messages["sender"] = $roww["sender"];
$messages["chatId"] = $roww["chatID"];
$messages["text"] = $roww["text"];
$messages["timestamp"] = $roww["timestamp"];
$myArray["message"][$count] = $messages;
$count = $count + 1;
}
else {
$myArray["message"]= 0;
}
}
$response[] = $myArray;
}
echo json_encode($response);
produces the following response:
[{"chatId":"1","user1_id":"32132132","user2_id":"2121","user1_name":"dwqd",
"user2_name":"dqdwdw","user1_profile_pic":"http:\/\/graph.facebook.com\/dwqwqdqdwdw\/picture?type=large","user2_profile_pic":"WDQdwqwqddqwdqwdq","message":{"1":{"message_id":"24242241","sender":"32132132","chatId":"1","text":"hello i am",
"timestamp":"2016-05-24 17:13:08"},"2":{"message_id":"421421","sender":"32132132",
"chatId":"1","text":"great","timestamp":"2016-05-24 17:15:08"}}},{"chatId":"2","user1_id":"23413524635","user2_id":"32132132","user1_name":false,
"user2_name":"dwqd","user1_profile_pic":
WDQdwqwqddqwdqwdq" ,"user2_profile_pic":"http:\/\/graph.facebook.com\/32132132\/picture?type=large",
"message":{"1":{"message_id":"24242241","sender":"32132132","chatId":"1","text":"hello i am",
"timestamp":"2016-05-24 17:13:08"},"2":{"message_id":"421421","sender":"32132132","chatId":"1",
"text":"great","timestamp":"2016-05-24 17:15:08"}}}]
You need to initialize $myArray at each iteration through the loop, e.g.
while($row = $user_chats->fetch_array()) {
$myArray = array();
I have an array containing several variables from my sql database.
{"gold":"0","silver":"0","bronze":"0","gdp":"12959563902","population":"3205000","country_name":"Albania"}, {"gold":"1","silver":"0","bronze":"0","gdp":"188681000000","population":"35468000","country_name":"Algeria"}
I have an additional variable called $score that uses information from the database to calculate this score. I want to know how I can loop through and add the correct score to each country in the array.
My Original Code:
$row = $res->fetchRow();
$resGold = $row['gold'];
$resSilver = $row['silver'];
$resBronze = $row['bronze'];
$resGdp = $row['gdp'];
$resPopulation = $row['population'];
$resCountry = $row['country_name'];
$gold_score = ($resGold * $gold_value);
$silver_score = ($resSilver * $silver_value);
$bronze_score = ($resBronze * $bronze_value);
if($population == true){
$score = (($gold_score + $silver_score + $bronze_score)/$resPopulation);
}
else if($gdp == true){
$score = (($gold_score + $silver_score + $bronze_score)/$resGdp);
}
$result = $res->fetchAll();
$result[] = array('score' => $score);
echo json_encode($result);
Your code will be something like this:
$json_data = '{"gold":"0","silver":"0","bronze":"0","gdp":"12959563902","population":"3205000","country_name":"Albania"},
{"gold":"1","silver":"0","bronze":"0","gdp":"188681000000","population":"35468000","country_name":"Algeria"}';
$countries_info_new = array();
$countries_info = json_decode($json_data);
foreach($countries_info as $country_info){
$country_info['score'] = Get_country_score($country_info['country_name']);
$countries_info_new[]=$country_info;
}
$new_json_data = json_encode($countries_info_new);