D
D
Dmitry Baskakov2019-09-17 09:10:35
PHP
Dmitry Baskakov, 2019-09-17 09:10:35

How to organize the union of array elements, which are themselves arrays?

There is a large input array consisting of several arrays of the following format:
id => ...
children => ...
meta => ...
The children field contains the child id of the objects in the same array.
As a result, several elements of the array should be combined into an array of themselves, and the rest should remain as they are.
The main problem is the number of elements. Plus, it is not possible to remove unnecessary elements that have already been copied. If you start multiple arrays, then you get an error about the lack of memory. It turns out that you need to use a maximum of 1 large array.
Does anyone have any ideas/options for something like this?
Again. Initially the array is:

[
 [
  id => ...
  children => ... 
  meta => ...
 ],
 [
  id => ...
  children => ... 
  meta => ...
 ],
 [
  id => ...
  children => ... 
  meta => ...
 ],
...
]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MrDywar Pichugin, 2019-09-19
@dmitrybascacov

General scheme:
Data per client can be transmitted as a flat list, i.e. array like yours.
The client builds the tree himself.
There can be a lot of records in the database, you DO NOT NEED to transfer them all to the server, sooner or later it will fall, and the network through which this data will be transmitted will fall.
Data filtering in almost any case should be done by the SQL server on its side, it is optimized for this.
Records in the database can be stored as a flat list.
-id
-parentId
-...
And one more table for the hierarchy (with the help of this table we get rid of recursion, but this adds complexity to keeping this table up to date) :
-id_ancestor
-id_child
into the hierarchy table and get all Id_descendants that have an ancestor with Id=2. So you can very easily get records of any nesting level, and calmly walk up and down.
If the query is heavy, then you can use the view (View), the view can be made materialized (i.e. a table with its results will be created, and it will itself be kept up to date when the source tables are updated. But this is overhead).
Slightly off topic:
On one project, we somehow made folders with files available via the Web. I just was engaged in storage of a tree in a DB, and tracking of all operations (copying, moving, deleting). On the front of the same theme on Angular. There 3 cases need to be tracked, as a result, everything is needed - the node is moved to root; a node from root is moved to a child node; a node is moved from one child node to another.

X
xmoonlight, 2019-09-25
@xmoonlight

As a result, several elements of the array should be combined into an array of themselves,
Recursive processing (with delimiter).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question