I am working on the web service and json response.
I got this response from the API :
[
[
{
"id":"1",
"unique_id":"579992ffd1",
"contact_name":"qweryyy",
"user_phone_number":"03331524145",
"created_at":"2016-08-01 15:53:59"
},
{
"id":"2",
"unique_id":"579992ffd1",
"contact_name":"qwer",
"user_phone_number":"03331524231",
"created_at":"2016-08-01 16:04:59"
},
{
"id":"3",
"unique_id":"579992ffd1",
"contact_name":"qwer",
"user_phone_number":"0333152111",
"created_at":"2016-08-01 16:05:08"
}
]
]
But i need to show the response like this JSON:
{
"unique_id":"579992ffd1",
"user":[
{
"id":"1",
"contact_name":"qweryyy",
"user_phone_number":"03331524145",
"created_at":"2016-08-01 15:53:59"
},
{
"id":"2",
"contact_name":"qweryyy",
"user_phone_number":"03331524145",
"created_at":"2016-08-01 15:53:59"
},
{
"id":"3",
"contact_name":"qweryyy",
"user_phone_number":"03331524145",
"created_at":"2016-08-01 15:53:59"
}
]
}
Here is my code to get the user array and return it to show the json response:
if ($result) {
$this->conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username, $password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$stmt = $this->conn->prepare("SELECT * FROM contact WHERE
user_phone_number = '$user_phone_number' ");
//$stmt->bind_param("s", $phone_number);
$stmt->execute();
$user = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$user = $stmt->fetchAll();
//print_r($user);
return $user;
} else {
return false;
}
SHow json response :
if ($user) {
$string = '';
$cart = array();
$response["status"] = TRUE;
for($x=0;$x<count($user);$x++)
{
$string = $user[$x];
array_push($cart, $string);
}
echo json_encode(array($cart));
}
Any help to show the required output ??
$query = 'SELECT * FROM contact WHERE user_phone_number = "'.$user_phone_number.'"';
$result = mysql_query($query) or trigger_error($query.'<br>'.mysql_error(),E_USER_ERROR);
$list = Array();
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$list[] = $row;
}
$cart = Array(
'unique_id' => '579992ffd1';
'user' => $list;
);
echo json_encode($cart);
Related
I Have Database :
enter image description here
how to query mysql in codeigniter model so that it can output json data like this :
enter code here</script">
$.ajax({
url: '?grid=true&tahun=' + tahuncikarang,
method: "GET",
success: function(data) {
var obj = JSON.parse(data);
}
Highcharts.chart('cikarang', {
chart: {
type: 'bar'
},
title: {
text: 'Highcharts multi-series drilldown'
},
subtitle: {
text: 'The <em>allowPointDrilldown</em> option makes point clicks drill to the whole category'
},
xAxis: {
type: 'category'
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true
}
}
},
series: [{
name: '2010',
data: obj.tahun1
}, {
name: '2014',
data: obj.tahun2
}],
drilldown: {
allowPointDrilldown: false,
series: [{
id: 'republican-2010',
name: 'Republican 2010',
data: [
['East', 4],
['West', 2],
['North', 1],
['South', 4]
]
}, {
id: 'democrats-2010',
name: 'Republican 2010',
data: ''
}, ]
}
});
}
});
I try in model :
function index($tahuncikarang)
{
$this->db->select('nama AS nama, CONCAT(nama,"-", tahun) AS drilldown, sum(nilai) AS y');
$this->db->where('tahun=2010');
$this->db->group_by('nama')
->group_by('tahun');
$tahuna1 = $this->db->get(self::$table5);
$tahuna2 = array();
foreach ($tahuna1->result() as $row) {
array_push($tahuna2, $row);
}
$this->db->select('nama AS nama, CONCAT(nama,"-", tahun) AS drilldown, sum(nilai) AS y');
$this->db->where('tahun=2014');
$this->db->group_by('nama')
->group_by('tahun');
$tahunb1 = $this->db->get(self::$table5);
$tahunb2 = array();
foreach ($tahunb1->result() as $row) {
array_push($tahunb2, $row);
}
$result = array();
$result['tahun1'] = $tahuna2;
$result['tahun2'] = $tahunb2;
return json_encode($result, JSON_NUMERIC_CHECK);
}
I read your question just before.
If you could use this query, you maybe get good results.
Thank you
$qy = $this->db->query("select concat(lower(nama),'-',tahun) as id,concat(nama,'-',tahun) as name,group_concat(concat(zone,'-' ,nilai),',') as data group by nama, tahun")->result_array();
$result = array();
foreach($qy as $row) {
$temp = array(
"id"=>$row['id'],
"name"=>$row['name'],
"data"=>array()
);
$array = explode(',',$row['data']);
foreach($array as $el) {
$temp['data'][]=explode('-',$el);
}
$result[] = $temp;
}
echo json_encode($result);
I made json code using json encode, the results are correct, but I want to add a satatus response to the object. How to ?
this my code
public function get(){
header('Content-Type: application/json');
$db = $this->M_order->db_order();
$response = array();
$data = array();
foreach ($db as $key) {
$data[] = array(
'id' => $key->id_user,
'name' => $key->name,
'destination' =>$key->destination
);
}
$response['data'] = $data;
echo json_encode($response, TRUE);
}
this result my json
{
"data": [
{
"id": "1",
"name": "amar",
"destination": "USA"
}
]
}
here I want to add a status header in object, like the following ...
{
"status": 200,
"error": false,
"data": [
{
"id": "1",
"name": "amar",
"destination": "USA"
},
]
}
how to create ?
As I understand your question,
$response = array();
$data = array();
foreach ($db as $key) {
$data[] = array(
'id' => $key->id_user,
'name' => $key->name,
'destination' =>$key->destination
);
}
$response['status'] = 200;
$response['error'] = false;
$response['data'] = $data;
Hi I encountered a problem. I will record the data I received from the database.
JSON=>
{
"success": true,
"timestamp": 1565251506,
"base": "EUR",
"date": "2019-08-08",
"rates": {
"AED": 4.119657,
"AFN": 87.689574,
"ALL": 121.192477,
"AMD": 533.113395,
"ANG": 1.998509,
"AOA": 398.760307,
"ARS": 51.036305,
"AUD": 1.654423
}
}
After Json decode
array:5 [
"success" => true
"timestamp" => 1565205306
"base" => "EUR"
"date" => "2019-08-07"
"rates" => array:168 [
"AED" => 4.118588
"AFN" => 87.74397
"ALL" => 121.002609
"AMD" => 534.279745
"ANG" => 2.001014
]
]
I want this=> But How do I get quote and rate?
$response = file_get_contents("rate.json");
$datas = json_decode($response, true);
foreach ($datas as $data) {
$rates = new Rate();
$rates->base = $datas['base'];
$rates->quote = 'AED';
$rates->rate = '4.119657';
$rates->save();
}
You're looping over the wrong thing here, you should be looping over the rates and saving the corresponding key and value:
$response = file_get_contents("rate.json");
$data = json_decode($response, true);
foreach ($data['rates'] as $quote => $rate) {
$rates = new Rate();
$rates->base = $data['base'];
$rates->quote = $quote;
$rates->rate = $rate;
$rates->save();
}
I'm trying to use a custom FormRequest with validation rules for JSON formatted data. If I use same code in controller instead of the FormRequest class then it works fine, see below:
array data (from ajax request):
[
{
"name": "id",
"value": "1"
},
{
"name": "title",
"value": "My fun project"
}
]
Controller:
public function update(Request $request, $id) {
//convert it to readable json
$jsonReq = $request->json()->all();
$jsonData = array();
foreach ($jsonReq as $json) {
$jsonData[$json["name"]] = $json["value"];
}
$rules = [
'id' => 'required|numeric:1',
'title' => 'required|max:255',
];
$validation = Validator::make($jsonData, $rules);
if ($validation->fails()) {
return $validation->errors();
}
}
Above works fine when used in the controller. However, I want to separate my validation in a separate class, extending the FormRequest. This generates some errors, most likely due to the array format.
class UpdateProjectValidationRequest extends FormRequest {
public function rules() {
$jsonReq = $this->json()->all();
$jsonData = array();
foreach ($jsonReq as $json) {
$jsonData[$json["name"]] = $json["value"];
}
return [
'id' => 'required|max:1', //does not work
$jsonData['title'] => 'required|max:255', //does not work
];
}
Controller:
public function update(UpdateProjectValidationRequest $request, $id) {
// validate against rules
$request->rules();
The error message:
{
"message": "The given data was invalid.",
"errors": {
"My fun project": [
"My fun project field is required."
],
"id": [
"The id field is required."
],
Clearly this has to do with the format. Any ideas how to solve this? Note that after the foreach loop the data is formatted to below:
{
"id": "1",
"title": "My Fun project",
}
Ok so i could not solve it using the laravel FormRequest, instead I modified the ajax call itself by serializing it to json instead of an array.
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
//old: var formdata = JSON.stringify(jQuery('#myForm').serializeArray());
var formdata = JSON.stringify(jQuery('#myForm').serializeObject());
Can someone pls help me on how to array_push to a multidimensional array.
This is my code for pushing.
$arrDataChart3["categories"] = array();
array_push($arrDataChart3["categories"], array(
"category"=>array ()
)
);
while($row = sqlsrv_fetch_array($myAcc2)) {
array_push($arrDataChart3["categories"]["category"], array(
"label" => $row["position"])
);
}
i want to push $row["position"] to "category" from my database.
Here's what the array should contain.
"categories": [
{
"category": [
{
"label": "Q1"
},
{
"label": "Q2"
},
{
"label": "Q3"
},
{
"label": "Q4"
}
]
}
],
Thanks in advance
i used this solved the problem
$arrDataChart3["categories"] = array();
$arr=array ();
while($row = sqlsrv_fetch_array($myAcc2)) {
array_push($arr, array(
"label"=>$row['position']
)
);
}
array_push($arrDataChart3["categories"], array(
"category"=>$arr
)
);