I have a problem with multidimensional data arrays. I have a data array like this:
[
[
"name" => "netSnmp",
"oid" => "1.3.6.1.4.1.8072"
"status" => "current"
], [
"name" => "netSnmpObjects",
"oid" => "1.3.6.1.4.1.8072.1"
], [
"name" => "netSnmpEnumerations",
"oid" => "1.3.6.1.4.1.8072.3"
], [
"name" => "netSnmpModuleIDs",
"oid" => "1.3.6.1.4.1.8072.3.1"
], [
"name" => "netSnmpAgentOIDs",
"oid" => "1.3.6.1.4.1.8072.3.2"
], [
"name" => "netSnmpDomains",
"oid" => "1.3.6.1.4.1.8072.3.3"
], [
"name" => "netSnmpNotificationPrefix",
"oid" => "1.3.6.1.4.1.8072.4"
], [
"name" => "netSnmpNotifications",
"oid" => "1.3.6.1.4.1.8072.4.0"
], [
"name" => "netSnmpNotificationObjects",
"oid" => "1.3.6.1.4.1.8072.4.1"
]
]
I am looking for a simple way to create an array tree, based on the oid value from the array above. Those oid values are a dot-separated path. The more parts, the deeper in the final tree the corresponding item should be put.
The desired output:
[
"text" => "netSnmp",
"oid" => "1.3.6.1.4.1.8072",
"nodes" => [
[
"oid" => "1.3.6.1.4.1.8072.1",
"text" => "netSnmpObjects"
], [
"oid" => "1.3.6.1.4.1.8072.3",
"text" => "netSnmpEnumerations",
"nodes" => [
[
"text" => "netSnmpModuleIDs",
"oid" => "1.3.6.1.4.1.8072.3.1"
], [
"text" => "netSnmpAgentOIDs",
"oid" => "1.3.6.1.4.1.8072.3.2"
], [
"text" => "netSnmpDomains",
"oid" => "1.3.6.1.4.1.8072.3.3"
]
]
], [
"oid" => "1.3.6.1.4.1.8072.4",
"text" => "netSnmpNotificationPrefix"
"nodes" => [
[
"text" => "netSnmpNotifications",
"oid" => "1.3.6.1.4.1.8072.4.0"
], [
"text" => "netSnmpNotificationObjects",
"oid" => "1.3.6.1.4.1.8072.4.1"
]
]
]
]
]
Any idea how I can solve it?
You can key your data by oid in a new associated array: that way you can look up a certain parent key in a fast way.
Then it is just a matter of getting the parent key of a any given key (chopping off the final dot-separated part) and see where you have it in your new associated array, and then appending it to its nodes array.
Here is a function that does that:
function makeTree($arr) {
$keyed = [];
foreach ($arr as $item) $keyed[$item["oid"]] = $item;
$root = null;
foreach ($keyed as &$item) {
$key = $item["oid"];
$parent = substr($key, 0, strrpos($key, "."));
if (isset($keyed[$parent])) {
$keyed[$parent]["nodes"][] =& $item;
} else {
$root = $key;
}
}
return $keyed[$root];
}
You can run it like this on your sample data:
$arr = [
[
"name" => "netSnmp",
"oid" => "1.3.6.1.4.1.8072",
"status" => "current"
], [
"name" => "netSnmpObjects",
"oid" => "1.3.6.1.4.1.8072.1"
], [
"name" => "netSnmpEnumerations",
"oid" => "1.3.6.1.4.1.8072.3"
], [
"name" => "netSnmpModuleIDs",
"oid" => "1.3.6.1.4.1.8072.3.1"
], [
"name" => "netSnmpAgentOIDs",
"oid" => "1.3.6.1.4.1.8072.3.2"
], [
"name" => "netSnmpDomains",
"oid" => "1.3.6.1.4.1.8072.3.3"
], [
"name" => "netSnmpNotificationPrefix",
"oid" => "1.3.6.1.4.1.8072.4"
], [
"name" => "netSnmpNotifications",
"oid" => "1.3.6.1.4.1.8072.4.0"
], [
"name" => "netSnmpNotificationObjects",
"oid" => "1.3.6.1.4.1.8072.4.1"
]
];
$result = makeTree($arr);
print_r($result);
Related
Say I have a collection that looks like this:
$subscriptions = collect([
[
"id" => 1,
"event" => "FormCompleted",
"subscriber" => [
"id" => 2929,
"name" => "Adam",
"email" => "adam#dude.com"
]
],
[
"id" => 3,
"event" => "FormCompleted",
"subscriber" => [
"id" => 1928,
"name" => "Pope",
"email" => "pope#dude.com"
],
],
[
"id" => 4,
"event" => "StatusChanged",
"subscriber" => [
"id" => 2929,
"name" => "Adam",
"email" => "adam#dude.com"
]
]
]);
This shows a list of events with its subscriber. What I want is to re-group this to show a list of subscribers with its events. How do I group these results to get a result like this?
[
[
"id" => 2929,
"name" => "Adam",
"email" => "adam#dude.com",
"subscriptions" => [
[
"id" => 1,
"event" => "FormCompleted"
],
[
"id" => 4,
"event" => "StatusChanged"
],
]
],
[
"id" => 1928,
"name" => "Pope",
"email" => "pope#dude.com",
"subscriptions" => [
[
"id" => 3,
"event" => "FormCompleted"
]
]
]
]
Here is my code... which works, but it is very messy and I feel like there is a better way to do it...
$subscribers = $subscriptions->groupBy('subscriber.id')
->map(function($group) {
$subscriber = $group[0]->subscriber;
$subscriber['subscriptions'] = $group->map(function($subscription) {
unset($subscription['subscriber']);
return $subscription;
});
return $subscriber;
})->values();
I think like that this should return you all subscribers who have groups, so guarantees return not empty subscribers with events
More details you can read this in documention
return Subscriber::has('groups')->get()->groupBy('id');
I have a function which gives an array of the below format
$result = [
[
"name" => "text",
"id" => "928610",
"entity_type" => "node"
],
[
"name" => "folder",
"id" => "987620",
"entity_type" => "folder"
],
[
"name" => "text",
"id" => "956720",
"entity_type" => "node"
],
];
Each Folder "entity_type" => "folder" item has again child which returns same format array.
like if we run a foreach loop $result and if it is "entity_type" => "folder" then we pass the id to a function it will also give a similar array format as that of result.
So i need if it is "entity_type" => "folder" the below key added to the "entity_type" => "folder" item
"children" => [
'#theme' => 'child_elements',
'#child_elements' => [
[
'name' => 'text',
"id" => "333421",
"entity_type" => "node"
],
[
'name' => 'folder',
"id" => "897622",
"entity_type" => "folder"
],
[
'name' => 'text',
"id" => "342214",
"entity_type" => "node"
],
],
],
and recursively it should keep on adding if "entity_type" => "folder"
The final array should be
$result = [
[
"name" => "text",
"id" => "928610",
"entity_type" => "node"
],
[
"name" => "folder",
"id" => "987620",
"entity_type" => "folder"
"children" => [
'#theme' => 'child_elements',
'#child_elements' => [
[
'name' => 'text',
"id" => "333421",
"entity_type" => "node"
],
[
'name' => 'folder',
"id" => "897622",
"entity_type" => "folder"
],
[
'name' => 'text',
"id" => "342214",
"entity_type" => "node"
],
],
],
],
[
"name" => "text",
"id" => "956720",
"entity_type" => "node"
],
];
public function buildTree($elements) {
$branch = [];
$branch = ['#theme' => 'child_elements'];
foreach ($elements as $key => $element) {
foreach($element as $keys => $values){
if ($element['bundle'] == 'folder') {
$child = $this->loadElements($element['id']);
$branch['#child_elements'] = $child;
$element[$key]['children'] = $branch['#child_elements'];
$this->buildTree($child);
array_push($branch, $element);
}else{
$branch['#child_elements'][] = $element;
}
}
}
return $branch;
}
you need to use some logic statement and use array_push when the condition is met.
I need to take an array that turns the key (split by /) of each element into a child array, and assigns the data in the right format in the new array.
There can be multiple levels of nesting, realistically never more then 10, but that is to be decided.
For example;
given the input of
$i_have_this = [
"Base/child" => [
[
"filename" => "child-1",
"last_modified" => "29/01/2020"
],
[
"filename" => "child-2",
"last_modified" => "29/01/2020"
],
[
"filename" => "child-3",
"last_modified" => "29/01/2020"
]
],
"Base/child/grandChild1" => [
[
"filename" => "grandChild1-1",
"last_modified" => "29/01/2020"
]
],
"Base/child/grandChild2" => [
[
"filename" => "grandChild2-1",
"last_modified" => "29/01/2020"
],
[
"filename" => "grandChild2-2",
"last_modified" => "29/01/2020"
],
[
"filename" => "grandChild2-3",
"last_modified" => "29/01/2020"
],
[
"filename" => "grandChild2-4",
"last_modified" => "29/01/2020"
],
[
"filename" => "grandChild2-5",
"last_modified" => "29/01/2020"
]
]
];
I would like the output of
$want_this = [
'name' => 'Base',
'children' => [
[
'name' => 'child',
'children' => [
["name" => "child-1"],
["name" => "child-2"],
["name" => "child-3"],
[
"name" => "grandChild1",
"children" => [
["name" => "grandChild1-1"]
]
],
[
"name" => "grandChild2",
"children" => [
["name" => "grandChild2-1"],
["name" => "grandChild2-2"],
["name" => "grandChild2-3"],
["name" => "grandChild2-4"]
]
],
]
]
]
];
So far I have;
foreach($i_have_this as $path => $value) {
$temp = &$want_this;
foreach (explode('/', $path) as $key) {
$temp = &$temp[$key];
}
$temp = $value;
}
but can't quite finish it off.
Example code run here
I think you could treat this the same way that most use "dot" notation for arrays (like in Laravel). Just replace "." with "/" in your case:
Example Code
function unflatten($data) {
$output = [];
foreach ($data as $key => $value) {
$parts = explode('/', $key);
$nested = &$output;
while (count($parts) > 1) {
$nested = &$nested[array_shift($parts)];
if (!is_array($nested)) $nested = [];
}
$nested[array_shift($parts)] = $value;
}
return $output;
}
print_r(unflatten($i_have_this));
I have a PHP multi-dimensional array organized with each node listing its parent nodes under it. I'm trying to transform the array so that the output lists hierarchically with each node listing any child nodes and only listing unique paths within the array.
for instance this input array:
$input = [
[
"name" => "home",
"parents" => [],
],
[
"name" => "newslist",
"parents" => [
[
"name" => "home",
"parents" => [],
],
],
],
[
"name" => "newsdetail",
"parents" => [
[
"name" => "newslist",
"parents" => [
[
"name" => "home",
"parents" => [],
],
],
],
[
"name" => "home",
"parents" => [],
],
],
],
[
"name" => "knowledge",
"parents" => [],
],
];
Should output this array:
$output = [
[
"name" => "home",
"children" => [
[
"name" => "newslist",
"children" => [
[
"name" => "newsdetail",
"children" => [],
],
],
],
],
],
[
"name" => "knowledge",
"children" => [],
],
];
This could probably be done in a much nicer way, but this method works. just procedural functions as a proof of concept.
<?php
$input = [
[
"name" => "home",
"parents" => [],
],
[
"name" => "newslist",
"parents" => [
[
"name" => "home",
"parents" => [],
],
],
],
[
"name" => "newsdetail",
"parents" => [
[
"name" => "newslist",
"parents" => [
[
"name" => "home",
"parents" => [],
],
],
],
[
"name" => "home",
"parents" => [],
],
],
],
[
"name" => "knowledge",
"parents" => [],
],
];
//recursively get all parents and the level the parent is at
function getParents($nodes,$level,&$parents)
{
foreach($nodes AS $key => $node)
{
$parents[ $node['name'] ] = array( "name" => $node['name'], "level" => $level);
if(isset($node['parents']) && !empty($node['parents']))
{
$level += 1;
getParents($node['parents'],$level,$parents);
}
}
}
//sort the parents by level
function sortParentsByLevel($a, $b)
{
if ($a['level'] == $b['level']) {
return 0;
}
return ($a['level'] > $b['level']) ? -1 : 1;
}
//find the output path based on parents array to add new value to
function setValueFromPath(&$paths, $parents, $value)
{
$dest = &$paths;
if(empty($parents))
{
if(!isset($dest[$value]))
$dest[$value] = array();
} else {
$finalNode = array_pop($parents);
foreach ($parents as $parent)
{
$dest = &$dest[$parent];
}
$dest[$finalNode][$value] = array();
}
}
//init new variable
$output = array();
//loop through each input node
foreach($input AS $key => $node)
{
//init a parent array
$parents = array();
//if we have parents use the getParents method to set them
if(isset($node['parents']) && is_array($node['parents']) && !empty($node['parents']))
{
getParents($node['parents'],1,$parents);
}
//sort the parents according to their level
uasort($parents, 'sortParentsByLevel');
//we're only interested in the associative key
$parentKeys = array();
foreach($parents AS $parent)
{
$parentKeys[] = $parent['name'];
}
//add the $node['name'] value in the appropriate parent array
setValueFromPath($output, $parentKeys, $node['name'] );
}
echo '<pre>';
print_r($output);
echo '</pre>';
die();
/*
Array
(
[home] => Array
(
[newslist] => Array
(
[newsdetail] => Array
(
)
)
)
[knowledge] => Array
(
)
)
*/
Using elasticsearch I try find all items by word "skiing".
My mapping (PHP array):
"properties" => [
"title" => [
"type" => "string",
"boost" => 1.0,
"analyzer" => "autocomplete"
]
]
Settings:
"settings"=> [
"analysis" => [
"analyzer" => [
"autocomplete" => [
"type" => "custom",
"tokenizer" => "standard",
"filter" => ["lowercase", "trim", "synonym", "porter_stem"],
"char_filter" => ["html_strip"]
]
],
"filter" => [
"synonym" => [
"type" => "synonym",
"synonyms_path" => "analysis/synonyms.txt"
]
]
]
]
Search query:
[
"index" => "articles",
"body" => [
"query" => [
"filtered" => [
"query" => [
"bool" => [
"must" => [
"indices" => [
"indices" => ["articles"],
"query" => [
"bool" => [
"should" => [
"multi_match" => [
"query" => "skiing",
"fields" => ["title"]
]
]
]
]
]
]
]
]
]
],
"sort" => [
"_score" => [
"order" => "desc"
]
]
],
"size" => 10,
"from" => 0,
"search_type" => "dfs_query_then_fetch",
"explain" => true
];
In the sysnonyms.txt have skiing => xanthic.
I want get all items with "skiing" (because it is input word), "ski" (by porter_stem tokenizer) and then "xanthic" (by synonyms file). But get result only with word "xanthic".
Please, tell me why? How I need configure the index?
In the synonyms file you need to have "skiing, xanthic". In the way you have it now you are replacing skiing with xanthic, but you want to keep both. And I think you need to reindex the data to see the change.
Thanx, but this is decision. I changed mapping:
"properties" => [
"title" => [
"type" => "string",
"boost" => 1.5,
"analyzer" => "standard",
"fields" => [
"english" => [
"type" => "string",
"analyzer" => "standard",
"search_analyzer" => "english",
"boost" => 1.0
],
"synonym" => [
"type" => "string",
"analyzer" => "standard",
"search_analyzer" => "synonym",
"boost" => 0.5
]
]
]
]
Settings:
"settings"=> [
"analysis" => [
"analyzer" => [
"synonym" => [
"type" => "custom",
"tokenizer" => "standard",
"filter" => ["lowercase", "trim", "synonym"],
"char_filter" => ["html_strip"]
]
],
"filter" => [
"synonym" => [
"type" => "synonym",
"synonyms_path" => "analysis/synonyms.txt"
]
]
]
]