How to build tree structure from array in PHP - php

I have following table:
$arr = array(
array('id'=>100, 'year'=>2019, 'month'=>9, 'name'=>'a'),
array('id'=>101, 'year'=>2019, 'month'=>12, 'name'=>'b'),
array('id'=>102, 'year'=>2020, 'month'=>1, 'name'=>'c'),
array('id'=>103, 'year'=>2020, 'month'=>2, 'name'=>'d'),
);
With the code below
$tree = array();
foreach ($arr as $row) {
$tree[$row['year']] = array(
$row['month'] => array (
'id' => $row['id'],
'name' => $row['name'],
),
);
}
I would like to get following result - this structure as a tree:
Array
(
[2019] => Array
(
[9] => Array
(
[id] => 100
[name] => a
)
[12] => Array
(
[id] => 101
[name] => b
)
)
[2020] => Array
(
[1] => Array
(
[id] => 102
[name] => c
)
[2] => Array
(
[id] => 103
[name] => d
)
)
)
Unfortunately I get only following one with single "branches":
Array
(
[2019] => Array
(
[12] => Array
(
[id] => 101
[name] => b
)
)
[2020] => Array
(
[2] => Array
(
[id] => 103
[name] => d
)
)
)
What is missing here? why previous rows disappear from the structure?

As you want the year and month as the main indexes, you need to use both of these when adding the data into the $tree...
$tree = array();
foreach ($arr as $row) {
$tree[$row['year']][$row['month']] = [ 'id' => $row['id'],
'name' => $row['name']];
}
with your test data, this gives...
Array
(
[2019] => Array
(
[9] => Array
(
[id] => 100
[name] => a
)
[12] => Array
(
[id] => 101
[name] => b
)
)
[2020] => Array
(
[1] => Array
(
[id] => 102
[name] => c
)
[2] => Array
(
[id] => 103
[name] => d
)
)
)

You have mistake in key's names - bl_year, bl_month not exist:
foreach ($arr as $row) {
$tree[$row['year']] = array(
$row['month'] => array (
'id' => $row['id'],
'name' => $row['name'],
),
);
}

Related

Group Array by category

I am facing problem In grouping array with the Key:-
I have an php array Which has following elecment in it.
$array = array(
'0' => array ( 'id' => 'food,Travel', 'names' => 'chimpanzee' ),
'1' => array ( 'id' => 'food', 'name' => 'meeting' ),
'2' => array ( 'id' => 'Z1', 'name' => 'dynasty' ),
'3' => array ( 'id' => 'X', 'name' => 'chocolate' ),
'4' => array ( 'id' => 'Travel', 'name' => 'bananas' ),
'5' => array ( 'id' => 'Travel', 'name' => 'fantasy' ),
'6' => array ( 'id' => 'Travel', 'name' => 'football' )
);
When I try with following code:-
$newarray= array();
foreach($array as $key => $value){
$newarray[$value['id']][$key] = $value;
}
I am getting below result Array Here food,travel is created another array but I want to please those to respective category "Food goes to food" and travel goes to travel"
(
[food,Travel] => Array
(
[0] => Array
(
[id] => food,Travel
[names] => chimpanzee
)
)
[food] => Array
(
[1] => Array
[id] => food,Travel
[names] => chimpanzee
)
(
[id] => food
[name] => meeting
)
)
[Z1] => Array
(
[2] => Array
(
[id] => Z1
[name] => dynasty
)
)
[X] => Array
(
[3] => Array
(
[id] => X
[name] => chocolate
)
)
[Travel] => Array
(
[4] => Array
(
[id] => Travel
[name] => bananas
)
[5] => Array
(
[id] => Travel
[name] => fantasy
)
[6] => Array
(
[id] => Travel
[name] => football
)
)
)
But I am want following result:- Food should Go to food category and travels should go to travels category like:-
Array
(
[food] => Array
(
// Food should come at food category
[0] => Array
(
[id] => food
[names] => chimpanzee
)
)
(
[1] => Array
(
[id] => food
[name] => meeting
)
)
[Z1] => Array
(
[2] => Array
(
[id] => Z1
[name] => dynasty
)
)
[X] => Array
(
[3] => Array
(
[id] => X
[name] => chocolate
)
)
[Travel] => Array
(
( // Travel should come at travel category
[0] => Array
(
[id] => food
[names] => chimpanzee
)
)
[4] => Array
(
[id] => Travel
[name] => bananas
)
[5] => Array
(
[id] => Travel
[name] => fantasy
)
[6] => Array
(
[id] => Travel
[name] => football
)
)
)
When id has ,, just explode it, check the demo
$result = [];
foreach($array as $k => $v){
if(strpos($v["id"],",")) {
$ids = explode(",", $v["id"]);
foreach ($ids as $id) {
$result[$id][$k] = $v;
}
}else{
$result[$v["id"]][$k] = $v;
}
}
var_dump($result);
No need to make it complex, like some have suggested, use explode()
https://3v4l.org/jVK6j
$newarray= [];
foreach($array as $key => $value) {
if(is_array(explode(",", $value["id"]))) {
foreach(explode(",", $value["id"]) as $category) {
$newarray[$category][$key] = $value;
$newarray[$category][$key]["id"] = $category;
}
} else {
$newarray[$value["id"]][$key] = $value;
}
}
var_dump($newarray);
You could even remove $key since these will be auto incremented.
foreach($array as $value) {
if(is_array(explode(",", $value["id"]))) {
foreach(explode(",", $value["id"]) as $category) {
$value["id"] = $category;
$newarray[$category][] = $value;
}
} else {
$newarray[$value["id"]][] = $value;
}
}

PHP array with n level deep

Assuming I have an array and recursively want to do some task. I have spent one day for this unable to solve this. May be my logic is not good.
Any help on how to do such thing in an efficient way would save my days.
I have an array with n level deep, looking like:
Array
(
[0] => Array
(
[name] => user1
[email] => user1#demo.com
[depth] => 1
)
[1] => Array
(
[name] => user2
[email] => user2#demo.com
[depth] => 1
[0] => Array
(
[0] => Array
(
[name] => user2.1
[email] => user2.1#demo.com
[depth] => 2
)
)
)
[2] => Array
(
[name] => user3
[email] => user3#demo.com
[depth] => 1
[0] => Array
(
[0] => Array
(
[name] => user3.1
[email] => user3.1#demo.com
[depth] => 2
[0] => Array
(
[0] => Array
(
[name] => user3.1.1
[email] => user3.1.1#demo.com
[depth] => 3
)
)
)
[1] => Array
(
[name] => user3.2
[email] => user3.2#demo.com
[depth] => 2
)
)
)
)
I want to change above array in exactly this format:
array(
0 => array(
'name' => 'user1',
),
1 => array(
'name' => 'user2',
'children' => array(
0 => array(
'name' => 'user2.1',
) ,
) ,
) ,
2 => array(
'name' => 'user3',
'children' => array(
0 => array(
'name' => 'user3.1',
'children' => array(
0 => array(
'name' => 'user3.1.1',
) ,
) ,
) ,
1 => array(
'name' => '3.2',
)
) ,
) ,
)
Edited:
I am using this code and working fine if i want to show data in tree format but unable to push data into array as i want.
function displayArrayRecursively($arr, $indent='') {
if ($arr) {
foreach ($arr as $key => $value) {
if (is_array($value)) {
displayArrayRecursively($value, $indent . '-->');
} else {
if ($key == 'name')
{
echo "$indent $value <br>";
}
else {
continue;
}
}
}
}
}
displayArrayRecursively($userListArray);
Can anyone suggest me how to do this?
Thank you
This function will do what you want:
function process_nodes($nodes) {
$new = array();
foreach ($nodes as $node) {
$new[] = array('name' => $node['name']);
if (isset($node[0])) {
$new[count($new)-1]['children'] = process_nodes($node[0]);
}
}
return $new;
}
print_r(process_nodes($data));
Output:
Array
(
[0] => Array
(
[name] => user1
)
[1] => Array
(
[name] => user2
[children] => Array
(
[0] => Array
(
[name] => user2.1
)
)
)
[2] => Array
(
[name] => user3
[children] => Array
(
[0] => Array
(
[name] => user3.1
[children] => Array
(
[0] => Array
(
[name] => user3.1.1
)
)
)
[1] => Array
(
[name] => user3.2
)
)
)
)

PHP array merge to subarray with keys

I have a problem with merging array's. I'll try array merge and combine but nothing is working.
First array
Array (
[type1] => Array (
[userid] => Array (
[0] => 35
[1] => 37
)
[from] => Array (
[0] => 07-06-2017
[1] => 09-06-2017
)
[till] => Array (
[0] => 07-07-2017
[1] => 09-07-2017
)
)
[type3] => Array (
[userid] => Array (
[0] => 13
)
[from] => Array (
[0] => 10-06-2017
)
[till] => Array (
[0] => 10-07-2017
)
)
)
Second array
The second array is filled with room details, but the assigned users are not added yet.
Array (
[type1] => Array (
[m2] =>
[price] =>
[rooms] => 1
[extra] =>
[rented_to] => Array
(
[0] => Array
(
[userid] =>
[from] =>
[till] =>
)
)
)
[type3] => Array
(
[m2] =>
[price] =>
[rooms] => 1
[extra] =>
[rented_to] => Array
(
[0] => Array
(
[userid] =>
[from] =>
[till] =>
)
)
)
)
I'll will put these arrays together to one array, so that the data is insert into the "rented_to" section. How can I get this array into an another array like this:
Array (
[type1] => Array (
[m2] =>
[price] =>
[rooms] => 1
[extra] =>
[rented_to] => Array
(
[0] => Array
(
[userid] => 35
[from] => 07-06-2017
[till] => 07-07-2017
)
[1] => Array
(
[userid] => 37
[from] => 09-06-2017
[till] => 09-07-2017
)
)
)
[type3] => Array
(
[m2] =>
[price] =>
[rooms] => 1
[extra] =>
[rented_to] => Array
(
[0] => Array
(
[userid] => 13
[from] => 10-06-2017
[till] => 10-07-2017
)
)
)
)
The code
$manager_add_new_room_rented_to is an array that contains the value of the first array in my example.
$manager_add_new_room_type_desc = $_POST['manager_add_new_room_type_desc'];
$manager_add_new_room_type_m2 = $_POST['manager_add_new_room_type_m2'];
$manager_add_new_room_type_rent_price = $_POST['manager_add_new_room_type_rent_price'];
$manager_add_new_room_type_rooms = $_POST['manager_add_new_room_type_rooms'];
$manager_add_new_room_type_extra = $_POST['manager_add_new_room_type_extra'];
$manager_add_new_room_rented_to = $_POST['manager_add_new_room_rented_to'];
$add_new_room_information = array();
foreach ( $manager_add_new_room_type_desc as $key => $room_type ) :
$add_new_room_information[$room_type] = array(
'm2' => $manager_add_new_room_type_m2[$key],
'price' => $manager_add_new_room_type_rent_price[$key],
'rooms' => $manager_add_new_room_type_rooms[$key],
'extra' => $manager_add_new_room_type_extra[$key],
'rented_to' => array(
array(
'userid' => '',
'from' => '',
'till' => ''
)
)
);
endforeach;
Loop through $manager_add_new_room_rented_to[$room_type] and create the new array that you want.
foreach ( $manager_add_new_room_type_desc as $key => $room_type ) :
$renters = $manager_add_new_room_rented_to[$room_type];
$rented_to = array();
foreach ($renters['userid'] as $index => $userid) :
$rented_to[] = array('userid' => $userid, 'from' => $renters['from'][$index], 'to' => $renters['to'][$index]);
endforeach;
$add_new_room_information[$room_type] = array(
'm2' => $manager_add_new_room_type_m2[$key],
'price' => $manager_add_new_room_type_rent_price[$key],
'rooms' => $manager_add_new_room_type_rooms[$key],
'extra' => $manager_add_new_room_type_extra[$key],
'rented_to' => $rented_to
)
);
endforeach;

array one format to another

I have one array in two format. I want to change array from
Array
(
[step_number] => 4
[app_id] => Array
(
[0] => 2
[1] => 3
)
[formdata] => Array
(
[0] => Array
(
[name] => app_id[]
[value] => 2
)
[1] => Array
(
[name] => app_id[]
[value] => 3
)
[2] => Array
(
[name] => fieldval[2][2][]
[value] => 1
)
[3] => Array
(
[name] => fieldval[3][3][]
[value] => 200
)
[4] => Array
(
[name] => fieldval[3][3][]
[value] => day
)
[5] => Array
(
[name] => title
[value] => new plan
)
[6] => Array
(
[name] => feature_plan
[value] => 3
)
[7] => Array
(
[name] => plan_type
[value] => free
)
[8] => Array
(
[name] => price
[value] =>
)
[9] => Array
(
[name] => sell_type
[value] => us
)
)
)
this format to
Array
(
[app_id] => Array
(
[0] => 2
[1] => 3
)
[fieldval] => Array
(
[2] => Array
(
[2] => Array
(
[0] => 1
)
)
[3] => Array
(
[3] => Array
(
[0] => 200
[1] => day
)
)
)
[title] => new plan
[feature_plan] => 3
[plan_type] => free
[price] =>
[sell_type] => us
)
these are are one array into two format. i have data in to first array format and i want to change that format to second array type format.
please tell me how i am trying this for 2 days but not succeed.
Here is a function you could use to produce that conversion:
function convert_formdata($input) {
$output = array();
foreach($input['formdata'] as $data) {
$keys = preg_split("#[\[\]]+#", $data['name']);
$value = $data['value'];
$target = &$output;
foreach($keys as $key) {
// Get index for "[]" reference
if ($key == '') $key = count($target);
// Create the key in the parent array if not there yet
if (!isset($target[$key])) $target[$key] = array();
// Move pointer one level down the hierarchy
$target = &$target[$key];
}
// Write the value at the pointer location
$target = $value;
}
return $output;
}
You would call it like this:
$output = convert_formdata($input);
See it run on eval.in for the given input. The output is:
array (
'app_id' =>
array (
0 => 2,
1 => 3,
),
'fieldval' =>
array (
2 =>
array (
2 =>
array (
0 => 1,
),
),
3 =>
array (
3 =>
array (
0 => 200,
1 => 'day',
),
),
),
'title' => 'new plan,',
'feature_plan' => 3,
'plan_type' => 'free',
'price' => NULL,
'sell_type' => 'us',
)

How do I add an additional child array recursively within last array in PHP

I am attempting to add another child array to the last child array.
Here is a sample of my array,
Array
(
[Auto-Trail] => Array
(
[name] => Auto-Trail
[children] => Array
(
[2001] => Array
(
[name] => 2001
[children] => Array
(
[Tracker] => Array
(
[name] => Tracker
[children] => Array
(
[CK] => Array
(
[name] => CK
[children] => Array
(
[Fiat] => Array
(
[name] => Fiat
)
)
)
[EK] => Array
(
[name] => EK
[children] => Array
(
[Fiat] => Array
(
[name] => Fiat
)
)
)
)
)
[Cheyenne] => Array
(
[name] => Cheyenne
[children] => Array
(
[630S] => Array
(
[name] => 630S
[children] => Array
(
[Fiat] => Array
(
[name] => Fiat
)
[Merc] => Array
(
[name] => Merc
[children] => Array
(
[313] => Array
(
[name] => 313
)
[316] => Array
(
[name] => 316
)
)
)
)
)
[630] => Array
(
[name] => 630
[children] => Array
(
[Fiat] => Array
(
[name] => Fiat
)
[Merc] => Array
(
[name] => Merc
[children] => Array
(
[313] => Array
(
[name] => 313
)
[316] => Array
(
[name] => 316
)
)
)
)
)
[634] => Array
(
[name] => 634
[children] => Array
(
[Fiat] => Array
(
[name] => Fiat
)
[Merc] => Array
(
[name] => Merc
[children] => Array
(
[313] => Array
(
[name] => 313
)
[316] => Array
(
[name] => 316
)
)
)
)
)
[634U] => Array
(
[name] => 634U
[children] => Array
(
[Fiat] => Array
(
[name] => Fiat
)
[Merc] => Array
(
[name] => Merc
[children] => Array
(
[313] => Array
(
[name] => 313
)
[316] => Array
(
[name] => 316
)
)
)
)
)
This is the array I wish to add to every last element,
For example, I need to add the following to [CK][children][Fiat][children] (and every last children's children) - this array will be static, every last child will use the same array.
[BOF] => Array
(
[name] => Furniture
)
[CHA] => Array
(
[name] => Chassis
)
So ... ][CK][children][Fiat] would become the following,
[CK] => Array
(
[name] => CK
[children] => Array
(
[Fiat] => Array
(
[name] => Fiat
[children] => Array
(
[BOF] => Array
(
[name] => Furniture
)
[CHA] => Array
(
[name] => Chassis
)
)
)
)
)
Please note, Not every last child is the same indentation level, it could be 10 more children indentations. It must use the last array within the array of each array.
Apologies if it's hard to understand, I'm struggling to word exactly the way I need it to work.
Thank you for your time and effort.
check out this solution (quick'n'dirty):
function injectArray(array $target, array $inject, $depth = 0){
$hasChildrenKey = array_key_exists('children', $target);
$hasChildren = $hasChildrenKey && !empty($target['children']);
if($depth % 2 == 0){
foreach($target as $k => $v)
if(is_array($v))
$target[$k] = injectArray($v, $inject, $depth+1);
}
elseif(!$hasChildren){
if(!$hasChildrenKey)
$target['children'] = array();
$target['children'] = array_merge_recursive($target['children'], $inject);
}
else if($hasChildrenKey){
$target['children'] = injectArray($target['children'], $inject, $depth+1);
}
return $target;
};
$testArray = array(
'Auto-Trail' => array('name' => 'asdf',
'children' => array(
'2001' => array('name' => '2001',
'children' => array(
'Tracker' => array('name' => 'Tracker',
'children' => array(
'CK' => array('name' => 'CK',
'children' => array(
'Fiat' => array('name' => 'Fiat')
)
)
)
)
)
)
)
)
);
$testInjectArray = array('BOF' => array('name' => 'Furniture'), 'CHA' => array('name' => 'Chassis'));
$result = injectArray($testArray, $testInjectArray);
print_r($result);

Categories