PHP remove items from recursive array if id don't match - php

I'm struggling to remove item from recursive array if parent id don't match. All I want to display separate tree for each tree number. I didn't find any solution with SQL so now I am retrieving top nodes of that tree number and removing array those items don't have that top node ids. I already have tree structure, below I'm providing the structure of array.
{
"196": {
"id": "196",
"username": "test1",
"parent_id": null,
"children": [
{
"id": "197",
"parent_id": "196",
"flower_id": null,
"username": "test1",
"children": []
},
{
"id": "198",
"parent_id": "196",
"flower_id": "1690587",
"username": "test3",
"children": [
{
"id": "213",
"parent_id": "198",
"flower_id": "5197062",
"username": "test33",
"children": []
}
]
},
{
"id": "199",
"parent_id": "196",
"flower_id": "1690587",
"username": "test2",
"children": [
{
"id": "205",
"parent_id": "199",
"flower_id": null,
"username": null,
"children": [
{
"id": "207",
"parent_id": "205",
"flower_id": null,
"username": null,
"children": []
}
]
},
{
"id": "212",
"parent_id": "199",
"flower_id": "6794158",
"username": "gunu",
"children": []
}
]
}
]
}
}
Here is what I'm doing doing
function recursive_unset(&$array, $parentIds = array()) {
foreach ($array as $key => &$value) {
if(!in_array($value['parent_id'], $parentIds)) {
unset($array[$key]);
}
if (is_array($value['children'])) {
$this->recursive_unset($value, $parentIds);
}
}
}
This is how I'm calling this function $data = $this->recursive_unset($array, [198,199]);
Any help is appreciated.
Thanks in advance.

Related

how to eager loading nested relations and not repeat them at top level?

a have a comments table that has these fields: id, body, parent_id
each comment can have comments, that's why it has a parent_id column.
class Comment extends Model
{
public function comments()
{
return $this->HasMany($this, 'parent_id');
}
}
It can have child comments up to two levels only.
In my controller I retrieve the information this way:
return Comment::with('comments.comments')->get();
The resulting response is like this:
[
{
"id": 1,
"body": "test",
"parent_id": null,
"comments": [
{
"id": 2,
"body": "test",
"parent_id": 1,
"comments": [
{
"id": 3,
"body": "test",
"parent_id": 2
},
{
"id": 4,
"body": "test",
"parent_id": 2
}
]
},
{
"id": 5,
"body": "test",
"parent_id": 1,
"comments": []
}
]
},
{
"id": 2,
"body": "test",
"parent_id": 1,
"comments": [
{
"id": 3,
"body": "test",
"parent_id": 2,
"comments": []
},
{
"id": 4,
"body": "test",
"parent_id": 2,
"comments": []
}
]
},
{
"id": 3,
"body": "test",
"parent_id": 2,
"comments": []
},
{
"id": 4,
"body": "test",
"parent_id": 2,
"comments": []
},
{
"id": 5,
"body": "test",
"parent_id": 1,
"comments": []
},
{
"id": 6,
"body": "test",
"parent_id": null,
"comments": []
}
]
What I would to retrive is this:
[
{
"id": 1,
"body": "test",
"parent_id": null,
"comments": [
{
"id": 2,
"body": "test",
"parent_id": 1,
"comments": [
{
"id": 3,
"body": "test",
"parent_id": 2
},
{
"id": 4,
"body": "test",
"parent_id": 2
}
]
},
{
"id": 5,
"body": "test",
"parent_id": 1,
"comments": []
}
]
},
{
"id": 6,
"body": "test",
"parent_id": null,
"comments": []
}
]
I would like that the child comments don't repeat again at top level, what can I do?
thank you.
Add whereNull(‘parent_id’) to your top level query.
return Comment::whereNull('parent_id')->with('comments.comments')->get();

php array replace upto same depth

I'm building a binary tree where I have two arrays. First array has empty tree structure and second array has actual values. Below are the structure of both arrays.
First Array
"157": {
"id": "157",
"username": "username",
"children": [
{
"id": "-1",
"parent_id": "0",
"username": "NULL",
"position": "",
"children": [
{
"id": "-1",
"parent_id": "0",
"username": "NULL",
"position": "",
"children": [
{
"id": "-1",
"parent_id": "0",
"username": "NULL",
"position": "",
"children": []
}
]
}
]
}
]
}
}
Second Array
"157": {
"id": "157",
"position": 1,
"username": "test1",
"parent_id": null,
"children": [
{
"id": "158",
"position": 1,
"parent_id": "157",
"username": "test1",
"children": [
{
"id": "159",
"position": 1,
"parent_id": "158",
"username": "test2",
"children": [
{
"id": "160",
"position": 1,
"parent_id": "159",
"username": "test3",
"children": []
}
]
}
]
}
]
}
}
I'm using array_replace_recursive function to replace empty values with actual value. It is working fine when both the arrays have same depth. For example if first array has 3 depth and second array also has 3 depth then it is working fine, but if second array has more values then first array then it is breaking array tree structure. So now I want to replace values upto depth of first array, no matter how big is second array, just replace values upto the depth first array.
Is this really possible?
Thank you!

What is the most efficient way to change a list to a nested object in php

I have a list of (the result of a query in DB) like this:
[
{
"id": "1",
"parent_id": null,
"title": "مدادنوکی",
"url": "/medadnoki"
},
{
"id": "2",
"parent_id": null,
"title": "جامعه",
"url": "/commiunity"
},
{
"id": "5",
"parent_id": "1",
"title": "درباره ی مدادنوکی",
"url": "/about"
},
{
"id": "6",
"parent_id": "1",
"title": "درباره ی مدادنوکی",
"url": "/about"
},
{
"id": "7",
"parent_id": "2",
"title": "همکاران",
"url": "/co-worker"
},
{
"id": "8",
"parent_id": "2",
"title": "اساتید",
"url": "/masters"
}
]
But I want to create an object like this:
[
{
"title": "مدادنوکی",
"url": "/medadnoki",
"subs" : [
{
"title": "درباره مدادنوکی",
"url": "/about"
},
{
"title": "درباره مدادنوکی",
"url": "/about"
},
{
"title": "درباره مدادنوکی",
"url": "/about"
},
{
"title": "درباره مدادنوکی",
"url": "/about"
}
]
},
{
"title": "جامعه",
"url": "/soc",
"subs" : [
{
"title": "همکاران",
"url": "/co-work"
},
{
"title": "اساتید",
"url": "/masters"
}
]
}
]
I have handled this process with two foreach in php and it means I process data twice and it is not efficient and will be slow.
Is there any Idea to doing this with just one foreach?
using one foreach means faster than two foreach twice and It will show the result in big data
Assuming you have the results in an order where the parents appear in the results before any children they may have, this should work:
$nested = [];
foreach($results as $r) {
if($r['parent_id'] === null) {
$nested[$r['id']] = [
'title' => $r['title'],
'url' => $r['url'],
'subs' => []
];
continue;
}
$nested[$r['parent_id']]['subs'][] = [
'title' => $r['title'],
'url' => $r['url']
];
}
$nested = array_values($nested);

Obtaining the last level of a json tree on php

I have a json tree with categories,
I would like to obtain the last level of elements for each different category.
For example on this json:
[
{
"category_id": "3",
"parent_id": "2",
"name": "Women",
"categories": [
{
"category_id": "11",
"parent_id": "3",
"name": "Clothing",
"categories": [
{
"category_id": "30",
"parent_id": "11",
"name": "T-shirts",
"categories": null
},
{
"category_id": "33",
"parent_id": "11",
"name": "jeans",
"categories": null
}
]
}
]
},
{
"category_id": "5",
"parent_id": "2",
"name": "Footwear ",
"categories": [
{
"category_id": "15",
"parent_id": "5",
"name": "Rings",
"categories": [
{
"category_id": "51",
"parent_id": "15",
"name": "Small Leathers",
"categories": null
}
]
},
{
"category_id": "16",
"parent_id": "5",
"name": "Bands",
"categories": [
{
"category_id": "41",
"parent_id": "16",
"name": "boots",
"categories": null
}
]
},
{
"category_id": "48",
"parent_id": "5",
"name": "Bracelets",
"categories": [
{
"category_id": "55",
"parent_id": "48",
"name": "Cocktail",
"categories": null
}
]
}
]
}
]
The result would be an array (T-shirts, Jeans, Small Leathers, boots, cocktail)
What I was thinking is to decode it on an array and search filter the array with all the categories that are null, but I'm not sure if it's the best option because the object have different levels.
(I'm sorry for the English)
Json string is not a valid. It can be made valid by enclosing the json string in {}.
$json = '{"categories": [
{
"category_id": "3",
"parent_id": "2",
"name": "Women",
"categories": [
{
"category_id": "11",
"parent_id": "3",
"name": "Clothing",
"categories": [
{
"category_id": "30",
"parent_id": "11",
"name": "T-shirts",
"categories": null
},
{
"category_id": "33",
"parent_id": "11",
"name": "jeans",
"categories": null
}
]
}
]
},
{
"category_id": "5",
"parent_id": "2",
"name": "Footwear ",
"categories": [
{
"category_id": "15",
"parent_id": "5",
"name": "Rings",
"categories": [
{
"category_id": "51",
"parent_id": "15",
"name": "Small Leathers",
"categories": null
}
]
},
{
"category_id": "16",
"parent_id": "5",
"name": "Bands",
"categories": [
{
"category_id": "41",
"parent_id": "16",
"name": "boots",
"categories": null
}
]
},
{
"category_id": "48",
"parent_id": "5",
"name": "Bracelets",
"categories": [
{
"category_id": "55",
"parent_id": "48",
"name": "Cocktail",
"categories": null
}
]
}
]
}
]}';
Decode the json string in to php opject
$json_object = json_decode($json);
Use this recursive function to fetch get all the last level categories in a array.
function getLastCategories($object){
$last_categories = array();
if(is_array($object->categories)){
foreach($object->categories as $categories){
$last_categories = array_merge( $last_categories, getLastCategories($categories));
}
}else{
$last_categories[]=$object->name;
}
return $last_categories;
}
print_r(getLastCategories($json_object));
Output:
Array
(
[0] => T-shirts
[1] => jeans
[2] => Small Leathers
[3] => boots
[4] => Cocktail
)
You can do this using recursive iterators.
$categories = json_decode($json);
// create the iterator
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($categories));
// iterate recursively
foreach ($iterator as $key => $subcategories) {
// if the 'categories' key is empty for the current level...
if ($key == 'categories' && !$subcategories) {
// then add the value of the 'name' key for the current level to your result array.
$result[] = $iterator->getSubIterator()->offsetGet('name');
}
}
This may not be the most efficient way to do it, but it makes the code pretty simple.

Elasticsearch Updating / Deleting Nested

I've gone through a few examples and documentations and kind find a solution update a nested object in the this result set.
I can add one (if one does not exist)
I can append to it (if one does exist)
Can't figure out how to delete a selected entry.
Is there a method I can use (using the php client) to add an entry if it does not exist / update an entry if it does exist / delete the second entry.
I'm inheriting this problem and am new to Elastic search.
Thanks.
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "products",
"_type": "categories",
"_id": "AUpRjtKZfXI7LIe9OpNx",
"_score": 1,
"_source": {
"name": "Primary",
"description": "Primary Category",
"slug": "Primary",
"created": "2014-12-16 00:25:22",
"parent": [
{
"name": "First One",
"description": "Test",
"id": "ae74ea4e2e865ed3fd60c18a06e69c65",
"slug": "first-one"
},
{
"name": "Second One",
"description": "Testing Again",
"id": "c8dbe5143c8dfd6957fa33e6cea7a0a8",
"slug": "second-one"
}
]
}
}
]
}
}
Do you want to do all three in the same operation?
Deleting the second nested object is achieved through a script which removes the second element:
PUT /products
{
"mappings": {
"categories": {
"properties": {
"parent": {
"type": "nested",
"properties": {
"name": { "type": "string" },
"description": { "type": "string" },
"id": { "type": "string", "index": "not_analyzed" },
"slug": { "type": "string" }
}
}
}
}
}
}
PUT /products/categories/1
{
"name": "Primary",
"description": "Primary Category",
"slug": "Primary",
"created": "2014-12-16 00:25:22",
"parent": [
{
"name": "First One",
"description": "Test",
"id": "ae74ea4e2e865ed3fd60c18a06e69c65",
"slug": "first-one"
},
{
"name": "Second One",
"description": "Testing Again",
"id": "c8dbe5143c8dfd6957fa33e6cea7a0a8",
"slug": "second-one"
}
]
}
POST /products/categories/1/_update
{
"script" : "ctx._source.parent.remove(1)",
"lang": "groovy"
}
GET /products/categories/1
So in PHP code (using the official PHP client), the update would look like:
$params = [
'index' => 'products',
'type' => 'categories',
'id' => 1,
'body' => [
'script' => 'ctx._source.parent.remove(1)',
'lang' => 'groovy'
]
];
$result = $client->update($params);

Categories