Create Hierarchical Array from MySQL result - php

I've seen other questions about this but not quite like my situation. I have the following table in MySQL:
term_id name slug taxonomy parent
1 Entry Form entry-form format 0
2 Page page format 3
3 Facebook facebook format 0
4 Entry Form facebook-entry-form format 3
5 Twitter twitter format 0
6 Single single format 2
I have the following OBJECT query:
$formats = $wpdb->get_results($wpdb->prepare("
SELECT * FROM table t
WHERE t.taxonomy = 'format'
"));
I wind up with the following array:
Array ( [0] => stdClass Object ( [term_id] => 1 [name] => Entry Form [slug] => entry-form [taxonomy] => format [parent] => 0 ) [2] => stdClass Object ( [term_id] => 2 [name] => Page [slug] => page [taxonomy] => format [parent] => 3 ) [3] => stdClass Object ( [term_id] => 3 [name] => Facebook [slug] => facebook [taxonomy] => format [parent] => 0 ) [4] => stdClass Object ( [term_id] => 4 [name] => Entry Form [slug] => entry-form-facebook [taxonomy] => format [parent] => 3 ) [5] => stdClass Object ( [term_id] => 5 [name] => Twitter [slug] => twitter [taxonomy] => format [parent] => 0 ) [6] => stdClass Object ( [term_id] => 6 [name] => Single [slug] => single [taxonomy] => format [parent] => 2 ) ) 1
All of the above needs to be turned into a hierarchical list on output that looks like this:
Entry Form
Twitter
Facebook
- Entry Form
- Page
-- Single
As such, I need to turn array $formats into a hierarchical array based on the parent field. A parent of 0 means it is a top level item. As such, since Single has parent of 2 it is the child of Page which in turn has parent of 3 and is a child of Facebook.
Can anyone help me turn my array into a hierarchical array and then show me how I can loop through it for output?

If performance due to volume of queries is not going to be a problem, the simplest solution is that, instead of doing a single query that populates an array, you do one query per node in your hierarchical tree, adding a "AND parent = $id", where $id is the term_id of the current node. Something like:
Do a SELECT WHERE .... AND parent = 0;
for each result in 1, $id = term_id, do a select WHERE ... AND
parent = $id
Repeat recursively until no more results
If performance is a problem you can still dump the query to your array and apply the same algorithm to the array, but you most likely will have memory issues doing it that way if you really have that much volume.

You need to put the data into assoc array while fetching it from the database:
//$groups - result array
$groups = array();
//$record contains the assoc array of the current record
while($record = $result->fetchAssoc()) {
if (!isset($groups[$record["parent"]]))
{
$groups[$record["parent"]] = array();
}
array_push($groups[$record["parent"]], $record);
}
In the end you will get an assoc array of hierarchy with parent as a key. Then traverse through it recursively, and you'll get the result:
function print_recursively(&$groups, $parent_id, $dashes = '')
{
if(isset($groups[$parent_id]))
{
foreach($groups[$parent_id] as $key => $value)
{
print $dashes . ' ' . $value["name"];
print_recursively(&$groups, $value["term_id"], $dashes . '-');
}
}
}
I didn't test this code, but the algorithm is correct.

Related

PHP search/filter array with given conditions, recursively

I am getting data from an api (that I cannot query agains, just get lump of data), and then I need to query against those data like I would do using database. Only It would be great if I could do it recursively.
Data example
[0] => Array
(
[id] => 1
[url] => https://domain.com/api/1.0/item/1/
[name] => some_item
[category] => some category
[created_by] => Array
(
[id] => 1
[screen_name] => tomino
)
[current_user_domain_access] => Array
(
[is_active] => 1
[is_administrator] => 1
)
[alerts_enabled] => 0
)
(much shortened version)
I receive an array of objects like that and then I need to select/filter/search by values.
Something like this
SomeModel::find(['category'=>'some category','current_user_domain_access' => ['is_administrator' => 1]]);
Is that something that would be possible in PHP? I was thinking about flattening the array, but then there might be key conflicts
1) select data : You can select data by (array_name->id),(array_name->url) and so on...
2)Filter : add conditions according to requirement
3)search : in_array(),array_search

PHP Find value in object

I have a result of an SQL query that looks like this
Array
(
[0] => stdClass Object
(
[field_number] => 1
[value] => Joe
)
[1] => stdClass Object
(
[field_number] => 2
[value] => Bloggs
)
[2] => stdClass Object
(
[field_number] => 3
[value] => 12566
)
[3] => stdClass Object
(
[field_number] => 4
[value] => 2000-07-24
)
)
It wont always return all the fields as some are not required therefore not saved to the database.
I know that first name is stored with field number 1. How can I look this up in the object.
EG
$first_name = $result => field_number == 1
I know thats not right, but Im sure there must be a simple way to get this info?
Thanks
If the values in the array are not in order (eg array[0] does not always contain field_number 1) then you will need to iterate the array:
foreach($array as $item){
if($item->field_number==1){
$first_name = $item->value;
break;
}
}
However, if this is the result of an SQL query, probably you need to rewrite the query to give you data in a more useable form

PHP build associated array from previous array

I'm trying to make a parent child like array out of a previous array of things, some are duplicates, some are not.
I have an array that spits out like so:
[0] => Array
(
[parent] => dogs
[child_cat_1] => category one
[child_cat_2] => category two
[title] => Title
[price] => 9.49
[sku] => 3558505550
[old_post_id] => 110
)
[1] => Array
(
[parent] => cats
[child_cat_1] => category one
[child_cat_2] => category six
[title] => Title
[price] => 16.49
[sku] => 2251752419
[old_post_id] => 113
)
[2] => Array
(
[parent] => cats
[child_cat_1] => category three
[child_cat_2] => category nine
[title] => Title
[price] => 59.99
[sku] => 7944100467
[old_post_id] => 114
)
[3] => Array
(
[parent] => dogs
[child_cat_1] => category one
[child_cat_2] => category two
[title] => Title
[price] => 69.99
[sku] => 85932810243
[old_post_id] => 117
)
I'm having a real hard time creating a new array based off these arrays, and turning it into an array of parents and children.
I tried doing what this post said, but I couldn't get it to work as I'm not entirely sure of what the 'parent' is going to be.
I tried doing this, but I can't figure out how to factor in child_cat_2, and also remove the duplicates. I've also read pretty much every "Building Hierarchy out of array" on Stackoverflow, but I just can't figure this one out.
foreach($new_array as $k => $v){
$array[$v['parent']] = $v['child_cat_1'];
}
Ideally, what I'm trying to accomplish is arranging each child_cat_2 under child_cat_1, and then both under parent, but then also remove the duplicates. I think the parent only has 11 types, but the two children have up to 100 each.
Can someone point me in the right direction to get these arrays sorted out.
What you've described is a 3-level nested array. The code you've posted certainly won't accomplish that. You have nodes with four properties other than your array structure, so that is what you should build in a loop. Then you place them into your structure depending on the other three properties.
$results = array();
foreach ($data as $datum){
$node = array(
'title' => $datum['title']
'price' => $datum['price']
'sku' => $datum['sku']
'old_post_id' => $datum['old_post_id']
);
if (!is_array($results[$datum['parent']])) {
$results[$datum['parent']] = array();
}
if (!is_array($results[$datum['parent']][$datum['child_cat_1']])) {
$results[$datum['parent']]
[$datum['child_cat_1']] = array();
}
if (!is_array($results[$datum['parent']][$datum['child_cat_1']][$datum['child_cat_2']])) {
$results[$datum['parent']]
[$datum['child_cat_1']]
[$datum['child_cat_2']] = array();
}
$results[$datum['parent']]
[$datum['child_cat_1']]
[$datum['child_cat_2']][] = $node;
}

Getting position number from an array

If I have the following array in session, can I get a item position number in each [cat]:
Array
(
[0] => stdClass Object
(
[id] => 1
[cat] => 1
[que] => Description here.
)
[1] => stdClass Object
(
[id] => 2
[cat] => 1
[que] => Description here.
)
[2] => stdClass Object
(
[id] => 3
[cat] => 1
[que] => Description here.
)
)
For example the following will give me the second description, but how do I get that it has position #2 (out of 3) in [cat] == 1:
$item = $_SESSION['questions'][2]->que;
The actual array is much larger and has more than 1 [cat]. The count I am trying to get is withing each such group.
I'm sure you're looking for a more native way, but worse case scenario, you could add another element to hold the index value.
By adding a dummy entry at the beginning of the array:
array_unshift($_SESSION['questions'], array());
$item = $_SESSION['questions'][2]->que;
foreach($_SESSION['questions'] as $key=>$val)
{
if($val->id == 3)
echo $key;
}
//or
foreach($_SESSION['questions'] as $key=>$val)
{
if($val->que == "Description here.")
echo $key;
}
//do what ever you want

Missing nodes in multidimensional array tree

Trying to create tree in multidimensional array with the following code
$source = array(
(array('id'=>406,'parent'=>0,'title'=>'level_0_406')),
(array('id'=>270,'parent'=>268,'title'=>'level_0_406_268_270')),
(array('id'=>271,'parent'=>268,'title'=>'level_0_406_268_271')),
(array('id'=>272,'parent'=>268,'title'=>'level_0_406_268_272')),
(array('id'=>273,'parent'=>268,'title'=>'level_0_406_268_273)')),
(array('id'=>269,'parent'=>268,'title'=>'level_0_406_268_269')),
(array('id'=>268,'parent'=>406,'title'=>'level_0_406_268')),
(array('id'=>407,'parent'=>406,'title'=>'level_0_406_407')),
(array('id'=>274,'parent'=>406,'title'=>'level_0_406_274')),
(array('id'=>500,'parent'=>407,'title'=>'level_0_406_407_500')),
);
$result = array();
$links = array(0=>&$result);
foreach ($source as &$element){
$links[$element['id']] = &$element;
$links[$element['parent']]['childs'][$element['id']] = &$element;
}
But result array does not include several nodes of source array, viz. nodes with id=269,270,271,272,273.
Array
(
[childs] => Array
(
[406] => Array
(
[id] => 406
[parent] => 0
[title] => level_0_406
[childs] => Array
(
[268] => Array
(
[id] => 268
[parent] => 406
[title] => level_0_406_268
)
[407] => Array
(
[id] => 407
[parent] => 406
[title] => level_0_406_407
[childs] => Array
(
[500] => Array
(
[id] => 500
[parent] => 407
[title] => level_0_406_407_500
)
)
)
[274] => Array
(
[id] => 274
[parent] => 406
[title] => level_0_406_274
)
)
)
)
)
I tried different code examples of tree generation but all of them have the same issue with source array like $source. Please help me understand such behavior.
Update
Now i understand what is wrong with array. But what if i have such data in DB, how to make selection properly? $source array should be specially sorted before using tree generation function.
The original $source array values are not properly created. It should be:-
$source = array(
(array('id'=>406,'parent'=>0,'title'=>'level_0_406')),
(array('id'=>268,'parent'=>406,'title'=>'level_0_406_268')),
(array('id'=>407,'parent'=>406,'title'=>'level_0_406_407')),
(array('id'=>274,'parent'=>406,'title'=>'level_0_406_274')),
(array('id'=>270,'parent'=>268,'title'=>'level_0_406_268_270')),
(array('id'=>271,'parent'=>268,'title'=>'level_0_406_268_271')),
(array('id'=>272,'parent'=>268,'title'=>'level_0_406_268_272')),
(array('id'=>273,'parent'=>268,'title'=>'level_0_406_268_273)')),
(array('id'=>269,'parent'=>268,'title'=>'level_0_406_268_269')),
(array('id'=>500,'parent'=>407,'title'=>'level_0_406_407_500')),
);
If you look carefully, you will see that previously, only the child element of the parent element ID 407 was available, since the element ID 407 has been defined before the occurrence of the child element.
It is the de-facto of your coding logic to have the parent elements defined first followed by the definitions of the child elements. Also the general practice & standard has always been the same.
In my answer, I have changed the occurrence of the elements properly. This should work.
Hope it helps.

Categories