How to change result in array? - php

i have a array result like this
{"data":{"NamaKecamatan":"BEJI","total":"2","laki":"1","cewe":"1"}}
{"data":{"NamaKecamatan":"BOJONGSARI","total":0,"laki":0,"cewe":0}}
{"data":{"NamaKecamatan":"CILODONG","total":"2","laki":"1","cewe":"1"}}
{"data":{"NamaKecamatan":"CIMANGGIS","total":"4","laki":"2","cewe":"2"}}
but i want to change array like this:
data: [{NamaKecamatan: "BEJI", total: "46", laki: "18", cewe: "28"},…]
0: {NamaKecamatan: "BEJI", total: "46", laki: "18", cewe: "28"}
1: {NamaKecamatan: "BOJONGSARI", total: "20", laki: "7", cewe: "13"}
2: {NamaKecamatan: "CILODONG", total: "93", laki: "48", cewe: "45"}
3: {NamaKecamatan: "CIMANGGIS", total: "96", laki: "47", cewe: "49"}
4: {NamaKecamatan: "CINERE", total: "13", laki: "7", cewe: "6"}]
this is my controller in php
public function countByKecamatan(){
$kecamatan = $this->db->query("SELECT IDKecamatan, NamaKecamatan FROM mskecamatan ORDER BY NamaKecamatan ASC")->result_array();
foreach ($kecamatan as $keykecamatan) {
$result = $this->MsLaporan->dataNullByKecamatan($dateStart, $dateEnd, $kategori, $keykecamatan['IDKecamatan']);
if ($result == NULL) {
$row = array(
"NamaKecamatan" => $keykecamatan['NamaKecamatan'],
"total" => 0,
"laki" => 0,
"cewe" => 0,
);
}else{
$row = $result[0];
}
$data = array(
"data" => $row,
);
echo json_encode($data);
}
}
please help me to change this data

$data = '[{"data":{"NamaKecamatan":"BEJI","total":"2","laki":"1","cewe":"1"}},
{"data":{"NamaKecamatan":"BOJONGSARI","total":0,"laki":0,"cewe":0}},
{"data":{"NamaKecamatan":"CILODONG","total":"2","laki":"1","cewe":"1"}},
{"data":{"NamaKecamatan":"CIMANGGIS","total":"4","laki":"2","cewe":"2"}}]';
$array_data = json_decode($data, ture);
$result = [];
foreach($array_data as $item) {
$result['data'][] = $item['data'];
}
return json_encode($result);

You can approach this as following
public function countByKecamatan(){
$kecamatan = $this->db->query("SELECT IDKecamatan, NamaKecamatan FROM mskecamatan ORDER BY NamaKecamatan ASC")->result_array();
$i = 0;
foreach ($kecamatan as $keykecamatan) {
$result = $this->MsLaporan->dataNullByKecamatan($dateStart, $dateEnd, $kategori, $keykecamatan['IDKecamatan']);
if ($result == NULL) {
$row = array(
"NamaKecamatan" => $keykecamatan['NamaKecamatan'],
"total" => 0,
"laki" => 0,
"cewe" => 0,
);
}else{
$row = $result[0];
}
($i > 0) ? ($data[] = $row) : ($data = array('data' => $row));
$i++;
}
echo json_encode($data);
}

The output your getting is down to 2 minor problems in the lines...
$data = array(
"data" => $row,
);
echo json_encode($data);
The first is that you are building the array with the extra level which you say you want to remove. The second line of code then echos each piece of data one at a time. You need to build up a list of all of the records and then return the full data in one go.
public function countByKecamatan(){
// Create empty array for data
$data = [];
$kecamatan = $this->db->query("SELECT IDKecamatan, NamaKecamatan FROM mskecamatan ORDER BY NamaKecamatan ASC")->result_array();
foreach ($kecamatan as $keykecamatan) {
$result = $this->MsLaporan->dataNullByKecamatan($dateStart, $dateEnd, $kategori, $keykecamatan['IDKecamatan']);
if ($result == NULL) {
$row = array(
"NamaKecamatan" => $keykecamatan['NamaKecamatan'],
"total" => 0,
"laki" => 0,
"cewe" => 0,
);
}else{
$row = $result[0];
}
// Add new row of data to data to be returned
$data[] = $row;
}
// Return all of the data in JSON format
return json_encode($data);
}
Note that this returns the value rather than echos it - you may need to change this if when you call the controller, your framework needs to encode it some other way (i.e. as part of a Response object).

Related

Insert multidimensional array into multidimensional json in PHP

I want to insert some data into sub in json data with my data in database
here is my code:
$sql = "SELECT * FROM pharma_data";
$result = mysqli_query($conn, $sql);
$data = array();
while ($row = mysqli_fetch_assoc($result)){
$row_array['id'] = $row['phar_id'];
$row_array['name'] = $row['name'];
$row_array['batch'] = $row['batch_no'];
$row_array['category'] = $row['category'];
$row_array['measurement'] = $row['measurement'];
$row_array['stock'] = $row['stock'];
$row_array['price'] = $row['price'];
$row_array['date'] = $row['date_added'];
$row_array['expiration'] = $row['expiration_date'];
$row_array['type'] = $row['medicin_type'];
$row_array['supplier'] = $row['supplier'];
array_push($data,$row_array);
}
$convert = json_encode($data);
echo $convert;
but the output of my code is:
[{"id":"8","name":"Test Product Name Pharmacy","batch":"Test Product Name Pharmacy","category":"Test Category Pharmacy","measurement":"1mg","stock":"2","price":"15","date":"February 18, 2021, 11:36 am","expiration":"2021-02-18","type":"Test Medicine Type Pharmacy","supplier":"Nicole Gonzaga"},{"id":"9","name":"Alaxan","batch":"Test user medicine Supplies","category":"Test Category Pharmacy","measurement":"1mg","stock":"66","price":"63.43","date":"February 28, 2021, 4:45 pm","expiration":"2021-02-28","type":"Test Medicine Type Pharmacy","supplier":"Nicole Gonzaga"},{"id":"10","name":"Medicol","batch":"987","category":"Test Category Pharmacy","measurement":"1mg","stock":"15","price":"123.23","date":"February 28, 2021, 5:42 pm","expiration":"2021-02-28","type":"Test Medicine Type Pharmacy","supplier":"Nicole Gonzaga"},{"id":"11","name":"test","batch":"test","category":"Test Category Pharmacy","measurement":"213","stock":"32","price":"123.78","date":"February 28, 2021, 6:43 pm","expiration":"2021-02-28","type":"Test Medicine Type Pharmacy","supplier":"Nicole Gonzaga"}]
Want output like this:
{
"total": 800,
"totalNotFiltered": 800,
"rows": [
{
"id": 0,
"name": "Item 0",
"price": "$0"
},
{
"id": 1,
"name": "Item 1",
"price": "$1"
}
]
}
enter image description here
You need to filter out $data before sending it to the response so it means we need a function myFilter to filter the $data elements and we can filter all the elements in the array using array_map(). The total and totalFiltered column seems to give the total number of rows in $data hence the count(). Try the code below:
function myFilter($a) {
$row['id'] = $a['id'];
$row['name'] = $a['name'];
$row['price'] = $a['price'];
return $row;
};
$filterData = array(
'total' => count($data),
'totalNotFiltered' => count($data),
'rows' => array_map("myFilter", $data)
);
$convert = json_encode($filterData);
echo $convert;
Demo code would be here: https://ideone.com/pZCUbG
You need to convert the returned data. Something like:
$data = array();
while ($row = mysqli_fetch_assoc($result)){
$row_array['id'] = $row['phar_id'];
$row_array['name'] = $row['name'];
// $row_array['batch'] = $row['batch_no'];
// $row_array['category'] = $row['category'];
// $row_array['measurement'] = $row['measurement'];
// $row_array['stock'] = $row['stock'];
$row_array['price'] = $row['price'];
// $row_array['date'] = $row['date_added'];
// $row_array['expiration'] = $row['expiration_date'];
// $row_array['type'] = $row['medicin_type'];
// $row_array['supplier'] = $row['supplier'];
$data[] = $row_array; // Same as array_push($data,$row_array);
}
$final_data = array(
'total' => count($data),
'totalNotFiltered' => '',
'rows' => $data
);
$convert = json_encode($final_data);
echo $convert;
Commented out the data that isn't needed in this context (maybe you need it to use elsewhere, not sure. If so just uncomment back)
Not sure with totalNotFiltered as I don't know how you are calculating this. Maybe you can work with that and this gives you an idea to work with.

Return valid Json array

I'm fairly new to Json and arrays and I'm just wondering whether someone can correct the code I've tried that is still outputting an invalid string.
$json = array(
'posts' => array(),
);
while($row = mysqli_fetch_array($result)) {
$posts = array();
$posts['count'] = $rowcount;
$posts['streamitem_id'] = $row['streamitem_id'];
$json['posts'] = $posts;
echo json_encode($json);
}
I have used http://jsonlint.com/ and posted my returned data from firebug errors on lines 6,11 and 16
} {
{
"posts": {
"count": 4,
"streamitem_id": "1976"
}
} {
"posts": {
"count": 4,
"streamitem_id": "1980"
}
} {
"posts": {
"count": 4,
"streamitem_id": "1099"
}
} {
"posts": {
"count": 4,
"streamitem_id": "1178"
}
}
Some have already commented with a valid answer however, I believe array_push is the most efficient method rather than redefining the $posts variable over and over.
$json = array(
'posts' => array()
);
while($row = mysqli_fetch_array($result)) {
array_push($json['posts'], $array(
'count' => $rowcount,
'streamitem_id' => $row['streamitem_id']
)
);
}
echo json_encode($json);
PS: I noticed that you're putting $rowcount in each post array. If this is not intended, I recommend the following change:
$json = array(
'posts' => array(),
'count' => $rowcount
);
And then in the while loop:
array_push($json['posts'], $array(
'streamitem_id' => $row['streamitem_id']
)
);
This way, you can reference the post count and it won't be a waste of memory.
console.log(json['count']);
I think you want this:
$posts = array();
$rowcount = 0;
while ($row = mysqli_fetch_array($result)) {
$posts[] = array(
'count' => $rowcount,
'streamitem_id' = $row['streamitem_id'],
);
$rowcount++;
}
$json['posts'] = $posts;
echo json_encode($json);
Put this outside of loop, you are overwriting and echoing each value instead whole at once
Inside loop
$posts[] = ["count"=> $rowcount,"streamitem_id"=>$row['streamitem_id']);
After loop
$json['posts'] = $posts;
echo json_encode($json);

Encode nested JSON array in php

I want to send nested JSON array.Which contain following format.
${"posts":[{
"abc":"123",
"xyz":"123",
"pro":[{
"name":"Brinjal",
"qty":"500 gms"
},
{
"name":"Brinjal",
"qty":"500 gms"
}]
}]
}
Here is my php code:
$rows = $stmt->fetchAll();
if ($rows) {
$order["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["order_id"] = $row["order_id"];
$post["order_totalamount"] = $row["order_totalamount"];
$post["address"] = $row["address"];
$post["pincode"] = $row["pincode"];
$post["delivery_timeslot"] = $row["delivery_timeslot"];
$post["order_date"] = $row["order_date"];
$query1= "query";
$rows1 = $stmt->fetchAll();
if ($rows1) {
foreach ($rows1 as $row1) {
$query2= "query";
$rows2 = $stmt->fetchAll();
$post["product"] = array();
if ($rows2) {
$products = array();
foreach ($rows2 as $row2) {
$products["product_name"]=$row2["product_name"];
$products["prod_qty"] = $row2["product_minquantity"];
}
array_push($post["product"],$products);
echo json_encode($products);
}
}
}
array_push($order["posts"], $post);
}
echo json_encode($order);
}
From above code I got result:
$ {"posts":
[{
"order_id":"18",
"order_totalamount":"40",
"address":"2, Chetan Society, Vadodara",
"pincode":"390023",
"delivery_timeslot":"Zone wise delivery",
"order_date":"2016-03-18 17:50:53",
"product":[{"product_name":"Brinjal","prod_qty":"500 gms"}]
}]
}
But my actual product array is:
${"product_name":"Banana","prod_qty":"1 Kg"}{"product_name":"Brinjal","prod_qty":"500 gms"}
Kindly help out. I am stuck on it. tried a lot but did not get success.
In
foreach ($rows2 as $row2) {
$products["product_name"]=$row2["product_name"];
$products["prod_qty"] = $row2["product_minquantity"];
}
You overwrite $products["product_name"]and $products["prod_qty"] with the values of the last $row2.
The line {"product_name":"Banana","prod_qty":"1 Kg"}{"product_name":"Brinjal","prod_qty":"500 gms"} actually consists of two echo's:
{"product_name":"Banana","prod_qty":"1 Kg"}
{"product_name":"Brinjal","prod_qty":"500 gms"}
But you don't see the difference. I suggest echoing a string in-between them or use something like var_dump() to see how many values you're echoing.
You should do something like:
for ($i = 0; $i < count($rows2); $i++) {
$products[$i]["product_name"]=$rows2[$i]["product_name"];
$products[$i]["prod_qty"] = $rows2[$i]["product_minquantity"];
}
This will result in: [{"product_name":"Banana","prod_qty":"1 Kg"},{"product_name":"Brinjal","prod_qty":"500 gms"}]
FYI $array[] = has the same rsults as array_push(), but had less overhead of calling array_push().
EDIT:
Below a complete example since it doesn't seem to workout for you:
//Demo $order
$order = array (
'posts' =>
array (
0 =>
array (
'order_id' => '18',
'order_totalamount' => '40',
'address' => '2, Chetan Society, Vadodara',
'pincode' => '390023',
'delivery_timeslot' => 'Zone wise delivery',
'order_date' => '2016-03-18 17:50:53',
),
),
);
//Demo $rows2
$rows2 = array(
array(
'product_name' => 'banana',
'product_minquantity' => '1 Kg'
),
array(
'product_name' => 'Brinjal',
'product_minquantity' => '500 gms'
)
);
$post['product'] = array();
if ($rows2) {
$products = array();
for ($i = 0; $i < count($rows2); $i++) {
$products[$i]['product_name'] = $rows2[$i]['product_name'];
$products[$i]['prod_qty'] = $rows2[$i]['product_minquantity'];
}
$post['product'] = $products;
echo json_encode($products); //[{"product_name":"banana","prod_qty":"1 Kg"},{"product_name":"Brinjal","prod_qty":"500 gms"}]
}
//$order['posts'][] = $post;
$order['posts'][0] = $order['posts'][0] + $post;
//In this example I only have 1 item in $order['posts'] so I know to add to key 0.
//In your case you need to know which key of $rows1 you need to do the adding.
//Change the foreach loop of $rows to a for loop as well so you can define your own keynames ($i).
echo '<br>==================================================================<br>';
echo json_encode($order);
/*
{
"posts":[
{
"order_id":"18",
"order_totalamount":"40",
"address":"2, Chetan Society, Vadodara",
"pincode":"390023",
"delivery_timeslot":"Zone wise delivery",
"order_date":"2016-03-18 17:50:53",
"product":[
{
"product_name":"banana",
"prod_qty":"1 Kg"
},
{
"product_name":"Brinjal",
"prod_qty":"500 gms"
}
]
}
]
}
*/

Function not returning all database rows

I have this function in Code igniter PHP where I am trying to get all rows from the database that match a input value.
How should I change the code to get all rows that match my search criteria?
Thank you
Model search function:
function findquestion($searchvalue){
$this->db->where('answer1', $searchvalue);
$res = $this->db->get('questions');
$count = $res->num_rows();
if($res->num_rows()==0){
return "...";
}
$moviearray = $res->row_array();
return $moviearray;
}
Controller Function:
public function getdatabasedata()
{
if($this->input->server('REQUEST_METHOD') == 'GET')
{
$year = $this->input->get('searchvalue');
if($year != ''){
$movie = $this->adminmodel->findquestion($year);
echo json_encode($movie);
}
}
}
When I look at Postman to check what the JSON object holds, this is what I get. But in fact I have three more rows in my database that match my search criteria.
{
"id": "10",
"question": "test questions",
"image": "test image",
"answer1": "answer1",
"answer2": "answer2",
"answer3": "answer3",
"answer4": "answer4"
}
function findquestion($searchvalue){
1) define array.
$data = array();
$this->db->where('answer1', $searchvalue);
$res = $this->db->get('questions');
if($res->num_rows()==0){
return "...";
}
2) loop trough results and store in array.
foreach ($res->result() as $row)
{
$data[] = array(
'id' => $row->id,
'question' => $row->question,
'image' => $row->image,
'answer1' => $row->answer1,
'answer2' => $row->answer2,
'answer3' => $row->answer3,
'answer4' => $row->answer4
);
}
//$moviearray = $res->row_array();
return $data;
}

Writing to JSON with PHP

I need help with my json output. At present my output is as so:
[
[
{
"ING_SW_CB": "5",
"SB_SW_CB": "3",
"NG3_SW_CB": "1",
"Mould_Close": "4",
"Leak_Test": "5",
"ML_Load": "6",
"Pre_Heat": "3",
"Dispense": "9",
"A310": "7",
............
}
]
]
I’d like it to be as following with "key" & "value" included in the output.
{"key":"ING_SW_CB", "value": "5"},
{"key":"SB_SW_CB", "value": "3"},
..............................
Hers is my PHP script:
$json_response = array();
while ($row = mysqli_fetch_array($result2, MYSQL_ASSOC)) {
$row_array['ING_SW_CB'] = $row['ING_SW_CB'];
$row_array['SB_SW_CB'] = $row['SB_SW_CB'];
$row_array['NG3_SW_CB'] = $row['NG3_SW_CB'];
$row_array['Mould_Close'] = $row['Mould_Close'];
$row_array['Leak_Test'] = $row['Leak_Test'];
$row_array['ML_Load'] = $row['ML_Load'];
$row_array['Pre_Heat'] = $row['Pre_Heat'];
$row_array['Dispense'] = $row['Dispense'];
$row_array['A310'] = $row['A310'];
$row_array['Gelation'] = $row['Gelation'];
$row_array['Platen'] = $row['Platen'];
$row_array['Mainline_Unload'] = $row['Mainline_Unload'];
$row_array['De_mould'] = $row['De_mould'];
$row_array['Clean_Up'] = $row['Clean_Up'];
$row_array['Soda_Blast'] = $row['Soda_Blast'];
$row_array['Miscellaneous'] = $row['Miscellaneous'];
//push the values in the array
array_push($json_response,$row_array);
}
$json_data = json_encode($json_response, JSON_PRETTY_PRINT);
file_put_contents('your_json_file.json', $json_data);
I need the keywords "key" & "value" added to the output so I can popuate a D3 chart.
You need to loop on the row's results and build more arrays:
while(...) {
$temp = array();
foreach($row as $key => $value) {
$temp[] = array('key' => $key, 'value' => $value);
}
$json_response[] = $temp;
}
Loop over the columns:
$json_response = array();
while ($row = mysqli_fetch_array($result2, MYSQLI_ASSOC)) {
$json_row = array();
foreach ($row as $key => $value) {
$json_row[] = array('key' => $key, 'value' => $value);
}
$json_response[] = $json_row;
}
$json_data = json_encode($json_response, JSON_PRETTY_PRINT);
file_put_contents('your_json_file.json', $json_data);
$json_response = array();
while ($row = mysqli_fetch_array($result2, MYSQL_ASSOC)) {
//push the values in the array
foreach($row as $k=>$v){
$my_array = array("key"=>$k, "value"=>$v);
}
array_push($json_response,$my_array);
}
$json_data = json_encode($json_response, JSON_PRETTY_PRINT);
file_put_contents('your_json_file.json', $json_data);

Categories