PHP - Creating tree node - php

I am working on a project that uses jQuery easy ui
I implemented the tree node but I encountered problems on it. I would like to use the drag and drop feature but I can't produce the right json string.
This is all I have.
This data was pulled from database :
<?php
$array = array( 0 => array(
"id" => 1,
"text" => "Root Dir",
"parent" => 0
),
1 => array(
"id" => 2,
"text" => "Folder one",
"parent" => 1
),
2 => array(
"id" => 3,
"text" => "Folder two",
"parent" => 2
),
3 => array(
"id" => 4,
"text" => "File",
"parent" => 3
)
);
?>
the final output should look like this
<?php
$array = array(
"id" => 1,
"text" => "Root Dir",
"children" => array(
"id" => 2,
"text" => "Folder one",
"children" => array(
"id" => 3,
"text" => "Folder one",
"children" => array(
"id" => 4,
"text" => "File"
)
)
)
);
print json_encode( $array );
?>
I am willing to adjust the database design if needed.

Related

Recursively getting a list of parents for each node in a nested PHP array

In PHP I have a set of nested arrays of data. I want to flatten these, so that for every node and leaf I get a list of its parents.
Here's an example of the original array - note, each part could be of an unknown depth and length:
$data = array(
"name" => "Thing",
"children" => array(
array(
"name" => "Place",
"rdfs:subClassOf" => "schema:Thing",
"children" => array(
array(
"name" => "Accomodation",
"rdfs:subClassOf" => "schema:Place",
"children" => array(
array(
"name" => "Apartment",
"rdfs:subClassOf" => "schema:Accomodation",
),
array(
"name" => "Hotel",
"rdfs:subClassOf" => "schema:Accomodation",
),
array(
"name" => "House",
"rdfs:subClassOf" => "schema:Accomodation",
)
)
)
)
),
array(
"name" => "CreativeWork",
"rdfs:subClassOf" => "schema:Thing",
"children" => array(
array(
"name" => "Article",
"rdfs:subClassOf" => "schema:CreativeWork",
"children" => array(
array(
"name" => "NewsArticle",
"rdfs:subClassOf" => "schema:Article",
),
array(
"name" => "OpinionArticle",
"rdfs:subClassOf" => "schema:Article",
),
)
)
)
)
)
);
(The data I'm actually parsing is this Schema.org JSON file - the above is a minimal example of it.)
And here's what I'd like to end up with:
$results = array(
"Place" => array("Thing"),
"Accomodation" => array("Thing", "Place"),
"Apartment" => array("Thing", "Place", "Accomodation"),
"Hotel" => array("Thing", "Place", "Accomodation"),
"House" => array("Thing", "Place", "Accomodation"),
"CreativeWork" => array("Thing"),
"Article" => array("Thing", "CreativeWork"),
"NewsArticle" => array("Thing", "CreativeWork", "Article"),
"OpinionArticle" => array("Thing", "CreativeWork", "Article"),
);
I'm assuming I need to recursively call a function to build the array but so far I'm not having much luck. In case this makes it harder, this is happening in a static method.
Something quick to get you started:
class Parser {
public static function parse($input,$prefix = []) {
$return = $prefix ? [$input['name']=>$prefix] : [];
if (isset($input['children'])) {
$prefix[] = $input['name'];
foreach ($input['children'] as $child) {
$return += self::parse($child,$prefix);
}
}
return $return;
}
}
var_dump(Parser::parse($data));
You probably need to add a few checks and comments to make it more readable.

Convert PHP Array from One to Multi-dimensional Based on Parent ID Values

I've got a one-dimensional array of objects that represent multi-dimensional data:
array(
array(
"id" => 1,
"parent_id" => 0,
"content" => 'des'
),
array(
"id" => 2,
"parent_id" => 3,
"content" => 'abc'
),
array(
"id" => 3,
"parent_id" => 1,
"content" => 'jjjj'
),
array(
"id" => 4,
"parent_id" => 5,
"content" => 'dsfsd'
),
array(
"id" => 5,
"parent_id" => 0,
"content" => 'dsfsd'
)
);
How should I convert it into a multi-dimensional array?
array(
array(
"id" => 1,
"parent_id" => 0,
"content" => 'des'
),
array(
"id" => 3,
"parent_id" => 1,
"content" => 'jjjj'
),
array(
"id" => 2,
"parent_id" => 3,
"content" => 'abc'
),
array(
"id" => 5,
"parent_id" => 0,
"content" => 'dsfsd'
),
array(
"id" => 4,
"parent_id" => 5,
"content" => 'dsfsd'
)
);
I'd like to sort by id and children after the parent, if parent_id = 0 it is the root element. Thanks everybody very much!
I think you need to sort the array by parent_id.
array_sort() a laravel helper function : https://laravel.com/docs/5.7/helpers#method-array-sort
$sorted = array_sort($array, 'parent_id');
output
array:5 [▼
0 => array:3 [▼
"id" => 1
"parent_id" => 0
"content" => "des"
]
4 => array:3 [▼
"id" => 5
"parent_id" => 0
"content" => "dsfsd"
]
2 => array:3 [▼
"id" => 3
"parent_id" => 1
"content" => "jjjj"
]
1 => array:3 [▼
"id" => 2
"parent_id" => 3
"content" => "abc"
]
3 => array:3 [▼
"id" => 4
"parent_id" => 5
"content" => "dsfsd"
]
]
this is my code (done)
function sort($array){
$newArray = [];
sortLoop($array, $newArray);
return $newArray;
}
function sortLoop($array, &$newArray, $parent_id = 0){
foreach ($array as $key => $item) {
if ($item['parent_id'] == $parent_id) {
$newArray[] = $item;
unset($array[$key]);
sortLoop($array,$newArray, $item['id']);
}
}
}
Wish this useful for someone.

Dynamically push arrays into multidimensional array

I'm trying to dynamically build an array for the Facebook Messenger SDK and populate it with data from a database.
I can't seem to get a properly structured array no matter what I try.
What I need:
$messages = [
"attachment" => [
"type" => "template",
"payload" => [
"template_type" => "generic",
"elements" => [[
"title" => $row['title'],
"item_url" => $row['item_url'],
"image_url" => $row['image_url'],
"subtitle" => $row['subtitle'],
"buttons" => [[
"type" => "web_url",
"url" => "www.google.com",
"title" => "View Website"],
["type" => "postback",
"title" => "Start Chatting",
"payload" => "start"]]
]
]]
]];
I need to create the data inside buttons based on what I have in the database, tried with array_merge and inserting the array as a string:
// Created arrays
if (!empty($row['button1_type'])) {
$buttons[] = array("type" => $row['button1_type'],"url" => $row['button1_url'],
"title" => $row['button1_title'],
"payload" => $row['button1_payload']);
}
if (!empty($row['button2_type'])) {
$buttons[] = array("type" => $row['button2_type'],"url" => $row['button2_url'],
"title" => $row['button2_title'],
"payload" => $row['button2_payload']);
}
// In the case when I had array_merge - $buttons were actually named as $buttons1 and $buttons2
$buttons = array_merge($buttons1, $buttons2);
// Tried to add it as a string
if (!empty($row['button2_type'])) {
$buttons = "\"type\" => ".$row['button2_type'].",\"url\" => .".$row['button2_url'].",
\"title\" => ".$row['button2_title'].",
\"payload\" => ".$row['button2_payload'];
}
$messages = [
"attachment" => [
"type" => "template",
"payload" => [
"template_type" => "generic",
"elements" => [[
"title" => $row['title'],
"item_url" => $row['item_url'],
"image_url" => $row['image_url'],
"subtitle" => $row['subtitle'],
"buttons" => [
$buttons
]
]
]]
]];
Screenshot showing the differences between correct and incorrect:
So basically $buttons are created inside an extra array, how can I get rid of it? Maybe I should change the whole approach?
With
"buttons" => [$buttons]
//new array ^ ^
a new array is being created with square brackets so to avoid it. use
"buttons" => $buttons

How to consolidate duplicate elements of this array in PHP?

I have an array like this:
$array = array(
0 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "memory"),
1 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "cpu"),
2 => array("ordernumber" => "1", "name" => "John", "product" => "desktop", "component" => "cpu"),
3 => array("ordernumber" => "2", "name" => "Pete", "product" => "monitor", "component" => "")
);
It contains data from different orders, but as you can see an order can contain multiple purchased products, and each product can contain different 'components'. There's alot of duplicate data in this array, so I would like to turn it into this:
$array = array(
0 => array(
"order" => array(
"ordernumber" => "1", "name" => "John"
),
"products" => array(
0 => array(
"name" => "laptop",
"components" => array("memory", "cpu")
),
1 => array(
"name" => "desktop",
"components" => array("cpu")
)
)
),
1 => array(
"order" => array(
"ordernumber" => "2", "name" => "Pete"
),
"products" => array(
0 => array(
"name" => "monitor",
"components" => array()
)
)
)
);
What would be a good way to do this?
Please use below code to make the solution what you want
<?php
$array = array(
0 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "memory"),
1 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "cpu"),
2 => array("ordernumber" => "1", "name" => "John", "product" => "desktop", "component" => "cpu"),
3 => array("ordernumber" => "2", "name" => "Pete", "product" => "monitor", "component" => "")
);
$final_array = [];
foreach($array as $k=>$v){
$final_array[$v['ordernumber']]['order']['ordernumber'] = $v['ordernumber'];
$final_array[$v['ordernumber']]['order']['name'] = $v['name'];
$final_array[$v['ordernumber']]['products'][$v['product']]['name'] = $v['product'];
$final_array[$v['ordernumber']]['products'][$v['product']]['components'][] = $v['component'];
}
// You can skip this foreach if there will not metter of KEY of an array in your code!
$final_array = array_values($final_array);
foreach($final_array as $k=>$v){
$final_array[$k]['products'] = array_values($final_array[$k]['products']);
}
echo "<pre>";
print_r($final_array);
?>
its should work!!

Insert an array to a specified location in named array

In the array below, how can I push the new array into the $options array at the specified location?
$options = array (
array( "name" => "My Options",
"type" => "title"),
array( "type" => "open"),
array("name" => "Test",
"desc" => "Test",
"id" => $shortname."_theme",
"type" => "selectTemplate",
"options" => $mydir ),
//I want the pushed array inserted here.
array("name" => "Test2",
"desc" => "Test",
"id" => "test2",
"type" => "test",
"options" => $mydir ),
array( "type" => "close")
);
if(someCondition=="met")
{
array_push($options, array( "name" => "test",
"desc" => "description goes here",
"id" => "testMet",
"type" => "checkbox",
"std" => "true"));
}
You can use array_splice. For your example:
if($some_condition == 'met') {
// splice new option into array at position 3
array_splice($options, 3, 0, array($new_option));
}
Note: array_splice expects the last parameter to be an array of new elements, so for your example you need to pass an array containing the new option's array.
Simply
array_splice($options, 3, 0, $newArr);
for insert a new array, not to a spesific location(between $r[4] and $r[5]):
$options[]=array ("key" => "val"); //insert new array
$options[]=$v; //insert new variable
to insert a new array after spesific variable:
function array_push(&$array,$after_element_number,$new_var)
{
array_splice($array, $after_element_number, 0, $new_var);
}
if(someCondition=="met")
{
array_push($options, 2, array( "name" => "test",
"desc" => "description goes here",
"id" => "testMet",
"type" => "checkbox",
"std" => "true"));
}
As connec says, you can use array_splice, but without forgetting to wrap your array in another array, like this:
if ('met' === $some_condition)
{
array_splice($options, 3, 0, array(array(
'name' => 'test',
'desc' => 'description goes here',
'id' => 'testMet',
'type' => 'checkbox',
'std' => 'true'
)));
}
Edit: connec has already specified its response.

Categories