remapping and grouping repeated values from an array in php - php

I am trying to remap an response from a query to the database and group like items in one array. for example, from this example below.
Response:
[
"Location"=> "City 1",
"AptDate"=> "2020-09-16",
"AptTime"=> "11:00",
"AptLength"=> "45",
"AptStatus"=> "1",
"Operatory"=> "1 RECALL",
"OperatoryNum"=> "2"
],
[
"Location"=> "City 2",
"AptDate"=> "2020-09-16",
"AptTime"=> "09:00",
"AptLength"=> "45",
"AptStatus"=> "1",
"Operatory"=> "1 RECALL",
"OperatoryNum"=> "2"
],
[
"Location"=> "City 1",
"AptDate"=> "2020-09-16",
"AptTime"=> "12:00",
"AptLength"-> "45",
"AptStatus"=>"1",
"Operatory"=> "1 RECALL",
"OperatoryNum"=> "2"
[,
looping through results:
$remappedData=[];
foreach ($result as $value)
{
$remappedData[] = [
'location' => $value['Location'],
// And so on
];
}
}
This doesnt really give me what i need as I am trying to group the array based on Location and add the AppDate base on that location. Something like this.
{
"Location": "City 1",
"AptDate": ["2020-09-16","2020-09-16"],
"AptTime": ["11:00","12:00"],
"AptLength": ["45","45"],
"AptStatus": ["1","1"],
"Operatory": ["1 RECALL","1 RECALL"],
"OperatoryNum": ["2","2"]
},
{
"Location": "City 2",
"AptDate": ["2020-09-16"],
"AptTime": ["09:00"],
"AptLength":[ "45"],
"AptStatus": ["1"],
"Operatory": ["1 RECALL"],
"OperatoryNum": "2"
},

So based on your scenario, you want grouping on Location and group all other attributes by keeping them in array.
foreach ($result as $value)
{
$remappedData[$value['Location']]['location'] = $value['Location'];
$remappedData[$value['Location']]['AptDate'][] = $value['AptDate']; // Notice we're creating an array here.
$remappedData[$value['Location']]['AptTime'][] = $value['AptTime'];
// so on all other attributes which needs to be grouped.
}
Note: Here we've created index as Location. If we don't want Location as key, we want as array(may be for frontend) use below code.
$temp = [];
$remappedData=[];
$intCurrentIndex = -1;
foreach ($result as $value)
{
if(isset($temp[$value['Location']])){
$oldIndex = $temp[$value['Location']];
$remappedData[$oldIndex]['AptDate'][] = $value['AptDate'];
$remappedData[$oldIndex]['AptTime'][] = $value['AptTime'];
}
else{
$temp[$value['Location']] = ++$intCurrentIndex;
$remappedData[$intCurrentIndex]['location'] = $value['Location'];
$remappedData[$intCurrentIndex]['AptDate'][] = $value['AptDate'];
$remappedData[$intCurrentIndex]['AptTime'][] = $value['AptTime'];
}
}

Related

make json array in json codeigniter

please help, i got stucked on making json using codeigniter.
this is what i want my json look like
{
"pelajar": [
{
"id": "1",
"name": "rumah sakit",
"usia": "45",
"tahun": "2020",
"alamat": "jalan kartini"
},
{
"id": "2",
"name": "rumah sakit umum",
"usia": "28",
"tahun": "2020",
"alamat": "jalan ibu",
"pendidikan": [
{
"id_pelajar": "2",
"sekolah": "SDN Lombok timur"
},
{
"id_pelajar": "2",
"sekolah": "SMPN Lombok timur"
}
]
}
]
}
but, i dont know why my code doesnt work to make like it.
this is how my code output :
{
"pelajar": {
"pelajar": [
{
"id": "1",
"name": "rumah sakit",
"usia": "45",
"tahun": "2020",
"alamat": "jalan kartini"
},
{
"id": "2",
"name": "rumah sakit umum",
"usia": "28",
"tahun": "2020",
"alamat": "jalan ibu"
}
],
"pendidikan": [
{
"id_pelajar": "2",
"sekolah": "SDN Lombok timur"
},
{
"id_pelajar": "2",
"sekolah": "SMPN Lombok timur"
}
]
}
}
this is my code :
$query = $this->db->query("select * from learn") -> result();
$response = array();
$data = array();
$datap = array();
foreach($query as $row){
$data[] = array(
"id"=> $row->id,
"name"=>$row->name,
"usia"=>$row->usia,
"tahun"=>$row->tahun,
"alamat"=>$row->alamat
);
$id = $row->id;
$pendidikanquery = $this->db->query("select * from pendidikan where learn_id='$id'" ) -> result();
foreach($pendidikanquery as $pen){
$datap[] = array(
"id_pelajar"=> $pen->id_pelajar,
"sekolah"=> $pen->sekolah
);
}
}
}
$response['pelajar']['pelajar'] = $data;
$response['pelajar']['pendidikan'] = $datap;
header('Content-Type: application/json');
echo json_encode($response, TRUE);
my problem is to set 'pendidikan' in the pelajar list where id_pelajar from pendidikan is same with id from pelajar table.
Honestly, there is so much to fix, this script should probably be completely rewritten, but I am not prepared to do that from my phone.
I would recommend using Active Record techniques in your model (not your controller).
Cache the subarray data before pushing into the first level. In doing so, you maintain the relationship between the parent id and the subarray data.
To be clear, my snippet will always create a pendidikan subarray -- even if it has no data. If you do not want this behavior, you will need to modify the script to check if the subarray is empty and then conditionally include it into the parent array. If this was my project, I would prefer a consistent data structure so that subsequent process wouldn't need to check again if specific keys exist.
Untested code:
$query = $this->db->query("SELECT * FROM learn")->result();
$data = [];
foreach($query as $row){
$datap = [];
$pendidikanquery = $this->db->query("SELECT * FROM pendidikan WHERE learn_id = {$row->id}")->result();
foreach ($pendidikanquery as $pen) {
$datap[] = [
"id_pelajar" => $pen->id_pelajar,
"sekolah" => $pen->sekolah
];
}
$data[] = [
"id" => $row->id,
"name" => $row->name,
"usia" => $row->usia,
"tahun" => $row->tahun,
"alamat" => $row->alamat,
"pendidikan" => $datap
];
}
header('Content-Type: application/json');
echo json_encode(["pelajar" => $data]);
if you want the output like your first image(the one with a red square)-
$response['pelajar']['pendidikan'] = $datap; // change this one to
// this ↓↓
$response['pelajar']['pelajar']['pendidikan'] = $datap; // change it like this

Compare variable of two different array?

Here i want compare two array.
I have two tables one is CATEGORY and second is USER(in which selected multiple category is stored in this format , , , ).
but when the USER want to update their category at that time the earlier selected category should return checked 1 and which is not selected should return checked 0 and here is my code.
case 'cat':
$sql="SELECT category from nesbaty_user where user_id='".$user_id."'";
$qry_res=mysqli_query($con,$sql);
$response1 = array();
while ($array = mysqli_fetch_array($qry_res))
{
foreach (explode(',', $array['category']) as $cat)
{
$response1[]=array('category' => $cat);
$response['Selected_category'] = $response1;
}
}
$qry="SELECT cat_id,category,image_url FROM nesbaty_category";
$qry_res=mysqli_query($con,$qry);
$jsonData = array();
while ($array = mysqli_fetch_assoc($qry_res))
{
$jsonData[] = $array;
$response['category'] = $jsonData;
}
echo json_encode($response);
//echo json_encode(array('data1' =>$response1));
//
mysqli_close($con);
break;
and here is my fetched array from the database.
{
"Selected_category": [
{
"category": "5"
},
{
"category": "6"
},
{
"category": "9"
}
],
"category": [
{
"cat_id": "1",
"category": "Drug",
"image_url": "1.jpg"
},
{
"cat_id": "2",
"category": "Bars",
"image_url": "2.jpg"
},
{
"cat_id": "3",
"category": "Bars",
"image_url": "2.jpg"
},
{
"cat_id": "4",
"category": "Hair Saloon",
"image_url": "2.jpg"
}
]
}
This is for handle this same structure as You provided.
<?php
$response = [];
$sql = "SELECT category from nesbaty_user where user_id='".$user_id."'";
$qry_res = mysqli_query($con, $sql);
$selectedCategories = mysqli_fetch_array($qry_res);
$selectedCategories = explode(',', $selectedCategories['category']);
$qry = "SELECT cat_id,category,image_url FROM nesbaty_category";
$qry_res = mysqli_query($con, $qry);
while ($categories = mysqli_fetch_assoc($qry_res)) {
$categories['checked'] = (int)\in_array($categories['cat_id'], $selectedCategories);
$response[] = $categories;
}
echo json_encode($response);
mysqli_close($con);
If any error writes a comment, I'll fix it.

create tree view like json from existing combined array

I have one combined array of order and its items combined into one array but i am trying to create json structure like order then its items list like wise.
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'abc',"price"=>250);
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'xyz',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'pqr',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'lmn',"price"=>250);
Output should be like
[
"0":[
{
"OrderNo": "1",
"partycode": "10",
"OrderDetails": [
{
"Item": "abc",
"price": 250
},
{
"Item": "xyz",
"price": 250
}
]
}
],
"1":[
{
"OrderNo": "2",
"partycode": "20",
"OrderDetails": [
{
"Item": "pqr",
"price": 250
},
{
"Item": "lmn",
"price": 250
}
]
}
]
]
This is What i Tried
$mainarray = array();
$orderarray = array();
$orderitemarray = array();
if (count(combinedarray) > 0) {
foreach (combinedarray as $obj) {
$orderarray[] = array("orderid" => $obj->orderid);
$orderitemarray[] = array("Item" => $obj->Item, "price" => $obj->price);
}
}
$mainarray[] = array_unique($orderarray);
$mainarray['OrderDetails'] = $orderitemarray;
echo json_encode($mainarray);
$mainarray = array();
foreach ($combinedarray as $x) {
$id = $x['orderid'];
unset($x['orderid']);
if (! isset($mainarray[$id])) {
$mainarray[$id]['OrderNo'] = $id;
}
$mainarray[$id]["OrderDetails"][] = $x;
}
// Now $mainarray has indexes equal to OrderNo. To count it from zero, use array_values
echo json_encode(array_values($mainarray), JSON_PRETTY_PRINT);
demo
By your given array
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'abc',"price"=>250);
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'xyz',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'pqr',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'lmn',"price"=>250);
Here is my solution for this
$new = array();
foreach($combinedarray as $r){
$new[$r['orderid']]['orderid'] = $r['orderid'];
$new[$r['orderid']]['partycode'] = $r['partycode'];
$new[$r['orderid']][] = array("item"=>$r['item'],"price"=>$r['price']);
}
$json = json_encode($new);
echo '<pre>';print_r($new);
echo $json;

Store object into array and group all array with the same value in PHP

I'm working on array right now and I need to arrange this based on value.
{
"data": {
"id": 2,
"title": "second evaluation form",
"emp_position": "System Architecture",
"rating": 5,
"segments": [
{
"segment_name": "Job Role ",
"question": "How old are you?"
},
{
"segment_name": "360 Segments",
"question": "What is your food?"
},
{
"segment_name": "360 Segments",
"question": "sample question"
},
]
}
}
What I need to do is to store this object into array and group all question based on segment_name like this:
{
"data":[
{
"id": 2,
"title": "second evaluation form",
"emp_position": "System Architecture",
"rating": 5,
"segments": [
{
"segment_name": "Job Role "
"question_collection": [
{
"id": 4,
"question": "How old are you?"
}
]
},
{
"segment_name": "360 Segments",
"question_collection":[
{
"id": 1,
"question": "What is your food?"
},
{
"id": 2,
"question": "sample question"
}
]
},
]
}
]
}
And this is what I've tried to do:
$array_value =[];
foreach ($query AS $key => &$data) {
$array_value['id'] = $data['id'];
$array_value['title'] = $data['title'];
$array_value['emp_position'] = $data['position'];
$array_value['rating'] = $data['rating_count'];
if ( is_array($data) ) {
$array_value['segments'][$key]['segment_name'] = $data['segment'];
$array_value['segments'][$key]['question'] = $data['question'];
}
}
Collection function might help you find your solution.
$json = '{"data":{"id":2,"title":"second evaluation form","emp_position":"System Architecture","rating":5,"segments":[{"segment_name":"Job Role ","question":"How old are you?"},{"segment_name":"360 Segments","question":"What is your food?"},{"segment_name":"360 Segments","question":"sample question"}]}}';
$array = json_decode($json, true);
$coll = collect($array['data']['segments']);
$coll = $coll->groupBy('segment_name');
dump($coll);
Hope this helps you.Let me know if any problem
Do it like below:-
<?php
$json = '{
"data": {
"id": 2,
"title": "second evaluation form",
"emp_position": "System Architecture",
"rating": 5,
"segments": [
{
"segment_name": "Job Role ",
"id": 4,
"question": "How old are you?"
},
{
"segment_name": "360 Segments",
"id": 1,
"question": "What is your food?"
},
{
"segment_name": "360 Segments",
"id": 2,
"question": "sample question"
}
]
}
}
';
$query = json_decode($json,true);
$segment_array = [];
foreach($query['data']['segments'] as $arr){
$segment_array[$arr['segment_name']]['segment_name'] = $arr['segment_name'];
$segment_array[$arr['segment_name']]['question_collection'][] = ['id'=>$arr['id'],'question'=>$arr['question']] ;
}
$query['data']['segments'] = array_values($segment_array);
echo json_encode($query,JSON_PRETTY_PRINT);
OUTPUT:- https://eval.in/902194
Try this solution, You can loop by array and group all keys
$json = '{
"data": {
"id": 2,
"title": "second evaluation form",
"emp_position": "System Architecture",
"rating": 5,
"segments": [
{
"segment_name": "Job Role ",
"question": "How old are you?"
},
{
"segment_name": "360 Segments",
"question": "What is your food?"
},
{
"segment_name": "360 Segments",
"question": "sample question"
}
]
}
}';
$data = json_decode($json,true);
$segments = $data['data']['segments'];
$new_segemnts = array();
foreach($segments as $segemnt)
{
$key = $segemnt['segment_name'];
$new_segemnts[$key]['segment_name']=$segemnt['segment_name'];
$new_segemnts[$key]['question_collection'][]=array("question"=>$segemnt['question']);
}
$data['data']['segments'] = array_values($new_segemnts);
echo json_encode($data,JSON_PRETTY_PRINT);
DEMO
Here try my answer. I've just editted your existing code so you won't confuse that much. Nothing much to explain here. I included some explaination in my comment.
CODE
$array_value =[];
foreach ($query AS $key => &$data) {
$array_value['id'] = $data['id'];
$array_value['title'] = $data['title'];
$array_value['emp_position'] = $data['position'];
$array_value['rating'] = $data['rating_count'];
if ( is_array($data) ) {
// Check if segment is already added
$has_segment = false;
$segment_key = null;
foreach($array_value['segments'] as $key2 => $val){
//If segment is already added get the key
if($val['segment_name'] == $data['segment']){
$segment_key = $key2;
$has_segment = true;
break;
}
}
// if segment does not exists. create a new array for new segment
if(!$has_segment){
$array_value['segments'] = array();
}
// If new segment, get the index
$segment_key = count($array_value['segments']) - 1;
// If new segment, create segment and question collection array
if(!array_key_exists('question_collection', $array_value['segments'][$segment_key])){
$array_value['segments'][$segment_key]['segment_name'] = $data['segment'];
$array_value['segments'][$segment_key]['question_collection'] = array();
}
//Add the id for question collectiona rray
$array_value['segments'][$segment_key]['question_collection'][] = array(
"id" => $data['question_id'],
"question" => $data['question']
);
}
}

merging two arrays in php from mysql and converting to json

I have two arrays which i want to merge and map the values together where it's id's are same . The problem is when i use array_merge function it only merges two arrays and resulting json is does not fit my model in android.
Here is php function :-
public function getfromorders(){
$sql = 'SELECT * FROM p_orders';
$query = $this -> conn -> prepare($sql);
$query -> execute(array());
$pro1=array();
$orders =array();
while($data = $query -> fetch(PDO::FETCH_OBJ))
{
$orders[] = $data;
$pro1[] = $data -> p_id;
}
$pro=array();
foreach ($pro1 as $id0) {
$sql = 'SELECT * FROM products WHERE p_id = :p_id';
$query2 = $this -> conn -> prepare($sql);
$query2 -> execute(array(':p_id' => $id0));
while($products = $query2 -> fetch(PDO::FETCH_OBJ))
{
$pro[] = $products;
}
}
return array_merge($pro,$orders);
}
Here is resulting json :-
{
"products": [
{
"p_id": "4",
"p_name": "Data Structures and algorithm in C++",
"p_info": "Adam Drozdek",
"p_sold": "Book Available : 20",
"p_image": "http://www.buildupcareer.com/gauti/Hunt/Food.jpg",
"p_type": "Veg",
"p_star": "0"
},
{
"p_id": "12",
"p_name": " Kadai Paneer",
"p_info": "An Indian vegetarian dish made with cottage cheese cooked with tomatoes-onions-bell peppers- and a blend of Indian spices",
"p_sold": "Spicy",
"p_image": "http://www.buildupcareer.com/gauti/Hunt/Burger.jpg",
"p_type": "Start-ups",
"p_star": "0"
},
{
"email": "7827789246",
"p_id": "4",
"noi": "1",
"order_id": "36"
},
{
"email": "7827789246",
"p_id": "12",
"noi": "1",
"order_id": "35"
}
],
"result": "success"
}
I want that resulting json should merge the (p_id,email,noi ,order_id) with the (p_id,p_name,p_info......) without changing the mysql database . Is there a way to achieve this?
Here is my expected json:-
{
"products": [
{
"p_id": "4",
"p_name": "Data Structures and algorithm in C++",
"p_info": "Adam Drozdek",
"p_sold": "Book Available : 20",
"p_image": "http://www.buildupcareer.com/gauti/Hunt/Food.jpg",
"p_type": "Veg",
"p_star": "0",
"email": "7827789246",
"noi": "1",
"order_id": "36"
},
{
"p_id": "12",
"p_name": " Kadai Paneer",
"p_info": "An Indian vegetarian dish made with cottage cheese cooked with tomatoes-onions-bell peppers- and a blend of Indian spices",
"p_sold": "Spicy",
"p_image": "http://www.buildupcareer.com/gauti/Hunt/Burger.jpg",
"p_type": "Start-ups",
"p_star": "0",
"email": "7827789246",
"p_id": "12",
"noi": "1",
"order_id": "35"
}
],
"result": "success"
}
This is how you can construct your JSON:
while($products = $query2 -> fetch(PDO::FETCH_OBJ)) {
$newElement = array();
foreach($products as $key => value) {
if ($key !== "p_id") {
$newElement[$key] = $value;
}
}
if (!isset($pro[$products["p_id"]])) {
$pro["p_id"] = array();
}
$pro["p_id"][]=$newElement;
}
Note that to avoid duplicating p_id, I have used it as a key. Each key is associated with an array of items.

Categories