Json Encode Multi dimension array format - php

im retrieving some data in my database table and than convert to json, but i need to create a array with this structire in my php loop
["postcode"=>"townName"...]
but instead is giving me
["postcode=>townName"...]
My code:
$sql = "SELECT * FROM uk_postcodes";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dname_list = array();
while($row = mysqli_fetch_array($result))
{
$dname_list[] = $row['postcode']."=>".$row['town'];
}
echo json_encode($dname_list);

In that line:
$dname_list[] = $row['postcode']."=>".$row['town'];
You're creating a string with "=>" in the middle (see string concatenation). You should specify the key of the array to be the postcode field, and the value - town field. Just change that line to:
$dname_list[$row['postcode']] = $row['town'];
http://php.net/manual/en/language.types.array.php

Related

how to retrieve value only of JSON by php from database?

may I know how to retrieve the value only array in json instead of the whole json object in php from the database?
<?php
require_once('dbConnect.php');
$sql = "SELECT RestaurantName FROM Restaurant";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$restaurantArray = array();
while($rows = mysqli_fetch_assoc($result)) {
$restaurantArray[] = $rows;
}
echo json_encode($restaurantArray);
mysqli_close($connection);
?>
For example,
["Afonso Cláudio", "Água Doce do Norte"]
instead of
[{"city":"Afonso Cláudio"},{"city":"Água Doce do Norte"}]
When fetching data from the database as assoc, you will get an associative array (which when converted to json will become a json object) as result.
What you are currently doing is adding the row (which is an associative array with one key-value) to your result array. If you only want the city, you can easily fetch only that data from the assoc-array.
Changing
$restaurantArray[] = $rows;
to
$resturantArray[] = $rows['city'];
should do the trick.
Additionally, if you wanted to reformat the data in the result, and not just push the city name to it, a array_map call could be used:
$result = array_map(function($assocArr) {
return $assocArr['city']; // Or whatever you want the value to be.
},
$resturantArray);
echo json_encode($result);
How about you change this line:
$restaurantArray[] = $rows;
With:
$restaurantArray[] = $rows['city']; // (or 'RestaurantName')

How to retrieve values from multiple rows as a single string

I have made MySQL database with three columns tags_id,tags,user_id, it must give out all the tags with respect to the user_id given.
eg: for this link:"http://allwaysready.16mb.com/Cuboid/tagsTest.php?user_id[]=7"
Output is:
{"result":[{"tags":"Pascol"},{"tags":"PHP"},{"tags":"Python"}]}
But I need my result to be in a sing string like this:
{"result":[{"tags":"Pascol","PHP",","Python"}]}
It should not be in array i want it in a single string.
Here is my php code :
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$user_id = $_GET['user_id'];
require_once('dbConnect.php');
$user_tags = array();
foreach ($_REQUEST['user_id'] as $key => $val) {
$user_tags[$key] = filter_var($val, FILTER_SANITIZE_STRING);
}
$user_ids = "'" . implode("','", $user_tags) . "'";
$sql = "SELECT * FROM user_tags WHERE user_id IN ({$user_ids})";
$r = mysqli_query($con,$sql);
//creating a blank array
$result = array();
//looping through all the records fetched
while($row = mysqli_fetch_array($r)){
//Pushing name and id in the blank array created
array_push($result,array(
"tags"=>$row['tags']
));
}
//Displaying the array in json format
echo json_encode(array('result'=>$result));
mysqli_close($con);
}
what should i change in my code.?
please help me guys thank you.
Your array_push mean
Push to your array new element with $key => $value
So solution in this case is remove array_push and try
$result['tags'][] = $row['tags'];

how i can use JSON result in calculation in php

i want to use json result in some calculation but whatever i try it didn't work.
<?php
//product id
$gp_id=$_GET['gp_id'];
//Importing the database connection
require_once('dbConnect.php');
$sql2 = "SELECT sum(rating_score) AS total_rate ,count(consumer_id) AS consumer
FROM productrate
WHERE gp_id='$gp_id'";
//Getting result
$result = mysql_query($sql2);
//Adding results to an array
$res = array();
while($row = mysql_fetch_array($result))
{
array_push($res, array(
// "gp_id"=>$row['gp_id'],
"total_rate"=>$row['total_rate'],
"consumer"=>$row['consumer']
)
); }
//Displaying the array in json format
$objJson=json_encode($res);
echo $objJson;
//calculate avg rate of specific product
$avg_rate = (int)"total_rate" / (int)"consumer";
echo $avg_rate ;
?>
as you see at the end i try to do some calculation but it didn't work.
this is the output...
[{"total_rate":"18","consumer":"4"}]
Warning: Division by zero in C:\xampp\htdocs\totalrate\highRate.php on line 33
$objJson=json_encode($res); makes json string. For example '{"a":1,"b":2,"c":3,"d":4,"e":5}'. You cannot use it like variables. Its string.
$avg_rate = "total_rate" / "consumer";
Looks like you trying to divide a string with another string.
Try using the array element instead, like:
$avg_rate = $res["total_rate"] / $res["consumer"];
finally i solve the problem ...
//product id
$gp_id=$_GET['gp_id'];
//Importing the database connection
require_once('dbConnect.php');
$sql2 = "SELECT sum(rating_score) AS total_rate ,count(consumer_id) AS consumer
FROM productrate
WHERE gp_id='$gp_id'";
//Getting result
$result = mysql_query($sql2) or die(mysql_error());
//Adding results to an array
$res = array();
while($row = mysql_fetch_array($result))
{
array_push($res, array(
"avg_rate"=>$row['total_rate']/ $row['consumer'],
"total_rate"=>$row['total_rate'],
"consumer"=>$row['consumer']
)
); }
//Displaying the array in json format
$objJson=json_encode($res);
echo $objJson;
?>

Php append value to an exsisting array

Hi I need to add some value-key pair to an array which is the output of mysql query. Below is the code,
$query = "select TITLE,DESCRIPTION from TABLE where ID='1234'";
$result = mysqli_query($conn, $query);
$numrows = mysqli_num_rows($result);
if($numrows>0)
{
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$myArray[] = $row;
}
}
echo json_encode($myArray);
Giving me the result like
[{"TITLE":"Special","DESCRIPTION":"This is DESCRIPTION."}]
Now I need to to add an another key-value pair to generate the json output like,
[{"TITLE":"Special","DESCRIPTION":"This is DESCRIPTION.","URL":"imgname.jpg"}]
So I added the code
$myArray["URL"]="imgname.jpg";
echo json_encode($myArray);
But giving me the output like,
{"0":{"TITLE":"Chef Special","DESCRIPTION":"Grilled Salmon and crab."},"URL":"imgname.jpg"}
Is there anything wrong with above code.
check your data with
var_dump($myArray);
and you will find, that it is a 2-dimensional array. you'd have to add your data with
$myArray[0]["URL"] = "imgname.jpg";
If you have to add after encoding it, reverse with:
$a = json_decode($myArray,true)
add a new pair of key, value with $a['URL'] = "imgname.jpg" and then encode again.

Easily add data from database to multidimensional array using php

How can I easily add data from MySQL to a multidimensional array in PHP? I am making a search box and I want to store the first name, and the last name in the array.
Why does not this work.
$result = mysqli_query($db, $sql) or die(mysqli_error());
$data = array();
while ($row = mysqli_fetch_array($result)) {
$data[$row['primary']] = $row['firstname'], $row['lastname'];
}
$data[$row['primary']] = array($row['firstname'], $row['lastname']);

Categories