Algorithm for tree data in php codeigniter - codeigniter

I am having trouble creating a category tree structure in php and codeigniter ramework environments.
So now I want the structure of the data.
Data Example:
{
"category": [
{
"id" : "1",
"text" : "test1"
"children": false,
}, {
"id" : "2",
"text" : "test2",
"children": [
{
"children": false,
"id" : "3",
"text" : "test3"
}, {
"children": false,
"id" : "4",
"text" : "test4"
}, {
"children": false,
"id" : "5",
"text" : "test5"
}, {
"children": false,
"id" : "6",
"text" : "test7"
}
]
}
]
}
I'm having trouble creating an array for each json object's children
The query I am trying:
public function setCategoryTree($categoryUp = null)
{
$param = array();
$query = ' SELECT id, name, categoryUp
FROM categoryTable
WHERE categoryUp = ? ';
return $this->commerce_db->query($query)->result();
}
The controller I'm trying to:
public function getCategoryTree(){
$this->load->model('category_m');
$result = $this->category_m->setCategoryTree();
$resultData = array();
foreach($result as $value) {
$treeTmpData = array();
$treeTmpData['id'] = $value->id;
$treeTmpData['text'] = $value->text;
$treeTmpData['children'] = ????
$resultData[] = $treeTmpData;
}
echo json_encode($resultData, JSON_UNESCAPED_UNICODE);
}
Good luck to me

You can use this code for your purpose. I use recursion for getting childern.
Table structure is :
CREATE TABLE `categorytable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`parent_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
);
Model methods are:
public function setCategoryTree() {
$categories = array();
$query = $this->db->query('SELECT id, name as text, parent_id as children FROM categoryTable WHERE parent_id IS NULL');
foreach ($query->result() as $row) {
$child = $this->getChilderen($row->id);
if (count($child) > 0) {
$row->children = $child;
} else {
$row->children = false;
}
$categories[] = $row;
}
return $categories;
}
private function getChilderen($parentId) {
$child = array();
$query = $this->db->query('SELECT id, name as text, parent_id as children FROM categoryTable WHERE parent_id = ' . $parentId);
if (count($query->result()) > 0) {
foreach ($query->result() as $i => $row) {
if ($row->children > 0) {
$row->children = $this->getChilderen($row->id);
}
$child[$i] = $row;
}
return $child;
} else {
return false;
}
}
Controller code:
public function getCategoryTree(){
$this->load->model('category_m');
$resultData = $this->category_m->setCategoryTree();
echo json_encode($resultData, JSON_UNESCAPED_UNICODE);
}
Hope, that will help you. Let me know if you stuck somewhere.

Related

How to merge object and array in one controller laravel

I got like this
[
{
"NameProduct": "iphone",
"IDProduct": 1,
"ListPrice": 100000,
"ImagePath": "iphone.png"
},
[
{
"IDCollection": 5,
"NameCollection": "Phone",
"Description": "my description",
}
],
{
"NameProduct": "SamSung",
"IDProduct": 2,
"ListPrice": 379000,
"ImagePath": "samsung.png"
},
[
{
"IDCollection": 5,
"NameCollection": "Phone",
"Description": "my description",
}
],
But I want like this:
{
"IDCollection": 5,
"NameCollection": "Phone",
"ProductList": [
{
"NameProduct": "iphone",
"IDProduct": 1,
"ListPrice": 100000,
"ImagePath": "iphone.png"
},
{
"NameProduct": "SamSung",
"IDProduct": 2,
"ListPrice": 100000,
"ImagePath": "samsung.png"
},
]
}
This is my code:
public function show(int $id)
{
$product=[];
$product_collection = CollectionProduct::where('IDCollection',$id)->get();
$collection = Collection::where('IDCollection',$id)->get();
foreach ($product_collection as $items) {
$x = Product::select('NameProduct','IDProduct','ListPrice')->find($items['IDProduct']);
$x->ImagePath = ProductImage::where('IDProduct',$items['IDProduct'])->first()['Path'];
array_push($product, $x,$collection);
}
return response()->json($product);
}
and idea how do that ?
You can use Eager Loading to get the relationships of CollectionProduct. https://laravel.com/docs/9.x/eloquent-relationships#eager-loading
For help you with the code I need to see your relationships of the DB but I think this can help you:
public function show(int $id)
{
$product_collection = CollectionProduct::with('collection.product.productImage')
->where('IDCollection',$id)
->get();
return response()->json($product_collection);
}

Laravel- How to Remove a key from collection?

I have data as below:
[
{
"id": "3",
"title": "Boruto's Photo",
"is_lottery": 1,
"price": 10
},
{
"id": "4",
"title": "Misuki's Photo",
"is_lottery": 0,
"price": 20
}
]
I want to filter which is is_lottery == false remove the price key from this collection. The output is:
[
{
"id": "3",
"title": "Boruto's Photo",
"is_lottery": 1,
"price": 10
},
{
"id": "4",
"title": "Misuki's Photo",
"is_lottery": 0,
}
]
You can do this
$json = '[
{
"id": "3",
"title": "Boruto\'s Photo",
"is_lottery": 1,
"price": 10
},
{
"id": "3",
"title": "Misuki\'s Photo",
"is_lottery": 0,
"price": 20
}
]';
$filtered = collect(json_decode($json, true))->map(function ($array) {
if (!$array['is_lottery']) {
unset($array['price']);
}
return $array;
});
For native PHP you can do
$data = json_decode($json, true);
foreach ($data as $index => $array) {
if (!$array['is_lottery']) {
unset($array['price']);
}
$data[$index] = $array;
}
$json = [
{
"id": "3",
"title": "Boruto's Photo",
"is_lottery": 1,
"price": 10
},
{
"id": "4",
"title": "Misuki's Photo",
"is_lottery": 0,
"price": 20
}
];
$filtered = collect(json_decode($json))->map(function($value, $key) {
if (!$value['is_lottery']) {
Arr::except($value, 'price');
}
return $value;
});
you can declare new variable called $newCollection as final collection. Use foreach() to iterate your collection then delete the is_lottery from collection by using unset() then push it to $newCollection, this is example how you can delete it using foreach:
$newCollection = [];
foreach ($photos as $key => $value) {
if ($value["is_lottery"] == 0) {
unset($value["price"]);
}
array_push($newCollection,$value);
}
or you can try using forget to remove it from collection (not tested) from this ref:
How to unset (remove) a collection element after fetching it?

Get value of nested array from json

I have some JSON data which get from an API. I need only the products name from there. How can I get this? I am already trying with foreach loop but I can't. I am using laravel framework version 6.0
[
{
"id": 2,
"name": "Bijj",
"categories": [
{
"id": 10,
"name": "Rice",
"sbu": 2,
"products" : [
{
"id": 25,
"name": "Rajkumar",
"skus": [],
"short_description": "বাংলাদেশের আবহাওয়া উপযোগী হাইব্রিড ধান",
},
{
"id": 50,
"name": "Sera",
"skus": [],
"short_description": "বাংলাদেশের আবহাওয়া উপযোগী হাইব্রিড ধান",
}
]
},
{
"id": 20,
"name": "Vhutta",
"sbu": 2,
"products" : [
{
"id": 129,
"name": "Pack-139",
"skus": [],
"short_description": "মোচায় ৮৬ % দানা ও ১৪ % শাঁস",
},
{
"id": 125,
"name": "Don-12",
"skus": [],
"short_description": "সারা বৎসর চাষ উপযোগী",
}
]
}
]
}
]
I want to get only the all products name form there.
$getSbu = Helper::CreateGuzzleHttpClient('sbu');
foreach ($getSbu as $value) {
if($value->id == 2) {
foreach ($value->categories as $category) {
$products = $category->products;
}
}
}
After decode you can simply use this helper
use Illuminate\Support\Arr;
Arr::only($array, ['categories.products.name']);
or
Arr::only($array, ['categories.*.name']);
you want get only product's name ??
and if your data array then you have to change $value['id']
$product_names = [];
foreach ($getSbu as $value) {
if($value->id == 2) {
foreach ($value->categories as $category) {
foreach ($category->products as $product) {
$product_names[] = $product->name;
}
}
}
}
dd($product_names);
foreach (json_decode($getSbu) as $value) {
Foreach works in an array so first you must decode it in order to parse it as an array.
Since you use object parsing you don't have to use parameter true in your json_decode function. If you want an array instead of an object you can use:
foreach (json_decode($getSbu,true) as $value) {
but then you access your value like array fields, for example value['id']
Your code should look like:
$getSbu = Helper::CreateGuzzleHttpClient('sbu');
foreach (json_decode($getSbu) as $value) {
if($value->id == 2) {
foreach ($value->categories as $category) {
$products = $category->products;
}
}
}
Leverage aravel collections
// this is just ur data but as json string
$var = '[{"id":2,"name":"Bijj","categories":[{"id":10,"name":"Rice","sbu":2,"products":[{"id":25,"name":"Rajkumar","skus":[],"short_description":"বাংলাদেশের আবহাওয়া উপযোগী হাইব্রিড ধান"},{"id":50,"name":"Sera","skus":[],"short_description":"বাংলাদেশের আবহাওয়া উপযোগী হাইব্রিড ধান"}]},{"id":20,"name":"Vhutta","sbu":2,"products":[{"id":129,"name":"Pack-139","skus":[],"short_description":"মোচায় ৮৬ % দানা ও ১৪ % শাঁস"},{"id":125,"name":"Don-12","skus":[],"short_description":"সারা বৎসর চাষ উপযোগী"}]}]}]';
$objCollection = collect(json_decode($var, true));
$productNames = $objCollection->pluck('categories.*.products.*.name');
dd($productNames);

Laravel : Search Query filter

I have searchDetails array in my search. I have done all other search and get data on filter, Problem is that when i search with stone_min, stone_max I get data if there is only one searchDetails array, if there is two data it is return null. How can i do this ? I want search with stone_min, stone_max for particular product_id.
what i try :
Example for data to search :
{
"limit": 1000,
"offset":0,
"user_id": "",
"min_price": "",
"max_price": "",
"searchDetails": [
{
"product_id": "1",
"attributeId": [],
"is_exclude": "no",
"stone_min": "5",
"stone_max": "15"
},
{
"product_id": "2",
"attributeId": [],
"is_exclude": "no",
"stone_min": "100",
"stone_max": "500"
}
]
}
My query for getting all data
$searchablePost = Post::with(['product','postattribute.attribute.category','user.userDetails'])
->whereIn('product_id', $userApprovalProductIDs)
->where('status', 'Active')
->whereIn('demand_or_supply', $demand_or_supply);
Search for min-max stone :
if (count($searchDetails) > 0) {
$j = 0;
foreach ($searchDetails as $value) {
if (strtolower(trim($value['is_exclude'])) == "no") {
$searchablePost = $searchablePost->where(function ($query) use ($value) {
if ($value['stone_min'] && $value['stone_max']) {
if (isset($j) && $j == 0){
$query->where('stone_min', '>=', $value['stone_min'])->where('stone_max', '<=', $value['stone_max'])->where("product_id", (int)$value['product_id']);
} else {
$query->where('stone_min', '>=', $value['stone_min'])->where('stone_max', '<=', $value['stone_max'])->where("product_id", (int)$value['product_id']);
}
}
});
}
}
}
$searchedPost = $searchablePost->offset($offset)->limit($limit)->orderBy('id','desc')->get();
If you want to search between stone_min and stone_max for particualar product then do:
$request = json_decode($request->searchDetails, true);
$stoneMinMax = collect($request)->pluck('stone_min', 'stone_max');
Product::where(function($q) use($productId) ($stoneMinMax){
$q->where('product_id', $productId)
->whereBetween('stone_column', $stoneMinMax->toArray());
})->get();

need to implement array push in forloop

----------------------Code --------------------------
public function event_requests(){
$Uid = Input::get('Uid');
$token = Input::get('token_code');
$time = Input::get('time');
if(App_user::where('ID', '=', $Uid)->where('token_code', '=', $token)->count() > 0){
$result = DB::table('Ball_invites')
->join('Ball_users','Ball_users.ID', '=', 'Ball_invites.people')
->select('Ball_users.*', 'Ball_invites.Eid')
->Where('Ball_users.Pid', '=', $Uid)
->orWhere('Ball_users.ID', '=', $Uid)
->get();
foreach ($result as $val){
$eis[] = $val->Eid;
$eids = array_unique($eis);
}
$event = DB::table('Ball_event')->whereIn('ID', $eids)->get();
$resultdataa = array();
foreach($result as $new){
$resultdataa[$new->Eid] = $new;
}
$resultdata = json_decode(json_encode($resultdataa), true);
$data = array();
foreach($event as $key){
$data[$key->ID] = $key;
}
$dataa = json_decode(json_encode($data), true);
$final = array();
foreach($dataa as $key2=>$val2){
foreach($resultdata as $key1=>$val1){
if($key2 == $key1){
$arrs[] = $val2;
$arrss[] = $val1;
print_r($val1);
}
}
}
return Response::json(array('status'=>200,'result'=>$final));
} else {
return Response::json(array('status'=>'401','msg'=>'session expired'));
}
}
--------------------- Need Record like this ----------------------
Editor Note: the data structure below looks like it is desired to be JSON,
but I'm not sure what to make of the nested array in a bad location.
{
"status": 200,
"result": [
{
"ID": 63,
"Uid": 86,
"event_type": 1,
"event_title": "Testing",
"event_location": "Home",
[
{
"ID": 141,
"Pid": 139,
"fname": "Veronica",
"lname": "khiwani",
"nick_name": "Ronnie",
},
{
"ID": 141,
"Pid": 139,
"fname": "Veronica",
"lname": "khiwani",
"nick_name": "Ronnie",
}
]
},
{
"ID": 64,
"Uid": 139,
"event_type": 2,
"event_title": "cricket match",
"event_location": "london",
}
]
}

Resources