implementing multi-level "iterator" in PHP - php

I'm trying to create a iterator like this one, for a list of comments:
// the iterator class, pretty much the same as the one from the php docs...
abstract class MyIterator implements Iterator{
public $position = 0,
$list;
public function __construct($list) {
$this->list = $list;
$this->position = 0;
}
public function rewind() {
$this->position = 0;
}
public function current() {
return $this->list[$this->position];
}
public function key() {
return $this->position;
}
public function next() {
++$this->position;
}
public function valid() {
return isset($this->list[$this->position]);
}
}
The comment iterator:
class MyCommentIterator extends MyIterator{
public function current(){
return new Comment($this->list[$this->position]);
}
}
And this is how I use it:
$comments = GetComments(); // gets the comments from the db
if($comments): ?>
<ol>
<?php foreach(new MyCommentIterator($comments) as $comment): ?>
<li>
<p class="author"><?php echo $comment->author(); ?></p>
<div class="content">
<?php echo $comment->content(); ?>
</div>
<!-- check for child comments and display them -->
</li>
<?php endforeach; ?>
</ol>
<?php endif; ?>
So everything is working fine, besides one thing: I can't figure it out how to process nested comments :(
The $comments array returns a flat list of comments, like:
[0] => object(
'id' => 346,
'parent' => 0, // top level comment
'author' => 'John',
'content' => 'bla bla'
),
[1] => object(
'id' => 478,
'parent' => 346, // child comment of the comment with id =346
'author' => 'John',
'content' => 'bla bla'
)
...
I need to somehow be able to check for child comments (on multiple levels) and insert them before the </li>'s of their parent comments...
Any ideas?

Recursion is your friend.
displaycomment(comment):
$html .= "<ol>" . comment->html;
foreach comment->child:
$html .= "<li>" . displaycomment(child) . "</li>";
$html .= "</ol>";
return $html;
All code appearing in this post is pseudo. Any resemblance to real code, working or broken, is purely coincidental.

You might want to look into the RecursiveIterator Interface PHP Manual. If you extend your iterator with the methods by that interface, you're able to iterate over your comments with an instance of RecursiveIteratorIterator PHP Manual sequentially.
However as your output is a flat list, you need to take care of the logic for the levels on your own, e.g. inserting <ol> per depth up, and </ol> per depth down.
Use the flags to control the order how children are traversed.

You are using a flat array, but in reality, the items of that array are a tree or hierarchical data structure.
You are basically displaying a sequential list. Maybe you should construct a tree / hierarchical data structure first, without displaying, and later display data from the tree list.
/* array */ function FlatArrayToTreeArray(/* array */ $MyFlatArray)
{
...
}
/* void */ function IterateTree(/* array */ $MyTreeArray)
{
...
}
/* void */ function Example() {
$MyFlatArray = Array(
0 => object(
'id' => 346,
'parent' => 0, // top level comment
'author' => 'John',
'title' => 'Your restaurant food its too spicy',
'content' => 'bla bla'
),
1 => object(
'id' => 478,
'parent' => 346, // child comment of the comment with id =346
'author' => 'Mike',
'title' => 'Re: Your restaurant food its too spicy',
'content' => 'bla bla'
),
2 => object(
'id' => 479,
'parent' => 478, // child comment of the comment with id =346
'author' => 'John',
'title' => 'Re: Your restaurant food its too spicy',
'content' => 'bla bla'
),
3 => object(
'id' => 479,
'parent' => 346, // child comment of the comment with id =346
'author' => 'Jane',
'title' => 'Re: Your restaurant food its too spicy',
'content' => 'bla bla'
)
);
$MyTreeArray = FlatArrayToTreeArray($myflatarray);
IterateTree($MyTreeArray);
} // function Example()
Cheers.

Related

Optimize an array function

Here is an example of test code. I wonder how to optimize this code, knowing that in my development code, the original array comes from an API that I retrieve, then that I transform according to my needs and calculations in a class with functions methods (there is a lot of transformation in $rep with ternary operators). The example here is for simplicity:
When you call the function testArray() several hundred times, the calculation time begins to become long, too long. I wonder if there's a way to optimize this and code more elegantly.
$data = array(
"lemon" => 'test1',
"tomato" => 'test2',
"cofee" => 'test3',
"tree" => 'test4'
);
function testArray($data)
{
$rep = array(
'yellow' => $data['lemon'],
'red' => $data['tomato'],
'brown' => $data['cofee'],
'green' => $data['tree']
);
return $rep;
}
echo testArray($data)['yellow']; // test1
echo testArray($data)['red']; // test2
echo testArray($data)['brown']; // test3
echo testArray($data)['green']; // test4
thank you, I'm stuck a bit to find a more efficient way.
You don't need to call the function multiple time. Just store it to a variable and use it later.
$data = array(
"lemon" => 'test1',
"tomato" => 'test2',
"cofee" => 'test3',
"tree" => 'test4'
);
function testArray($data)
{
$rep = array(
'yellow' => $data['lemon'],
'red' => $data['tomato'],
'brown' => $data['cofee'],
'green' => $data['tree']
);
return $rep;
}
$transformedData = testArray($data);
echo transformedData['yellow']; // test1
echo transformedData['red']; // test2
echo transformedData['brown']; // test3
echo transformedData['green']; // test4

Eloquent recursive relation

I have an issue where I'm trying to get all descendants of an object and keep only those with a specific property.
I have these relations:
public function getChildren()
{
return $this->hasMany(self::class, 'parent_id', 'id');
}
public function allChildren()
{
return $this->getChildren()->with('allChildren');
}
And I get this type of array for example:
$array = [
0 => ['name' => 'aaa', 'type' => 0, 'parent' => null, 'children' => [
1 => ['name' => 'bbb', 'type' => 1, 'parent' => null, 'children' => []],
2 => ['name' => 'ccc', 'type' => 0, 'parent' => null, 'children' => [
3 => ['name' => 'ddd', 'type' => 1, 'parent' => 2, 'children' => []]
]]
]],
4 => ['name' => 'eee', 'type' => 0, 'parent' => null, 'children' => []]
];
For this example, I would like to remove all objects that are of type 1 and get a clean array without those only.
I don't really understand why it is possible to get all descendats of an object but not be able to pass conditions.
Thanks in advance.
A collection only solution would be something like this (place the custom macro in a Service Provider of your application):
Collection::macro('whereDeep', function ($column, $operator, $value, $nested) {
return $this->where($column, $operator, $value)->map(function ($x) use ($column, $operator, $value, $nested) {
return $x->put($nested, $x->get($nested)->whereDeep($column, $operator, $value, $nested));
});
});
Then where needed call:
$yourArray->whereDeep('type', '!=', 1, 'children');
On your example, the macro works like this:
Filter all the elements where: type != 1
(the outer array will beuntouched as both items has type => 0)
For each element of the current array:
Retrive the children property and apply the same filtering to this subarray starting with the first point of this instructions.
Replace the children property with the new children property just filtered.
Anyways, you should try to deep dive into why the relation filtering doesn't work. That solution would be more efficient if optimized correctly.
I found a great solution where there is no need of all this recursion or any of these relationship calls so I share it:
Using: "gazsp/baum"
// get your object with roots method
$contents = Content::roots()->get();
// and simply run through the object and get whatever you need
// thanks to getDescendantsAndSelf method
$myArray = [];
foreach($contents as $content) {
$myArray[] = $content->getDescendantsAndSelf()->where('type', '!=', 1)->toHierarchy();
}
return $myArray;
This works for me the same way as the other method above.

add dash to sub menu within array in foreach loop

I have created a tree level menu but I wanted to separate all sub menus by simply adding -- to every sub menu like
main menu
-- 1st level
---- 2nd level
------ 3rd level
and so on
while doing it in LI it is so easy I can simply put tag before running my function but in select option I am unable to achive my target can anyone here would be able to help me out with this please
function fetch_menu($data) {
foreach($data as $menu) {
echo "<option value='".$menu->cid."'>".$menu->cname."</option>";
if(!empty($menu->sub)) {
fetch_sub_menu($menu->sub);
}
}
}
function fetch_sub_menu($sub_menu, $dash = '--'){
foreach($sub_menu as $menu){
echo "<option value='".$menu->cid."'>".$dash.$menu->cname."</option>";
if(!empty($menu->sub)) {
fetch_sub_menu($menu->sub, '--');
}
}
}
The problem is that while applying the above shown code that dash are not increasing for every 2nd or 3rd level menu
Here is how my data is organized in array form
array (
[cid] => 1,
[cname] => 'Main Menu',
[pcid] => 0,
[sub] => array(
[cid] => 2,
[cname] => '1st Level',
[pcid] => 1,
[sub] => array(
[cid] => 3,
[cname] => '2nd Level',
[pcid] => 2,
[sub] => array(
)
)
)
)
You need to add the new dashes to your $dash variable before recursivly calling the function again. That should work
function fetch_sub_menu($sub_menu, $dash = '--'){
foreach($sub_menu as $menu){
echo "<option value='".$menu->cid."'>".$dash.$menu->cname."</option>";
if(!empty($menu->sub)) {
fetch_sub_menu($menu->sub, $dash.'--'); // <-- adding two dashes to $dash
}
}
}

Recursive table which child parent relationship

I have a problem with a recursive function that takes too many resources to display a child-parent relation in a dropdown list. For example:
home
-menu 1
-menu 2
home 1
-menu 3
-menu 4
I've written some code for a recursive call to the database each time, so that's the reason why my code takes so many resources to run.
Below is my code:
--call recursive
$tmp = $this->get_nav_by_parent(0);
$a_sel = array('' => '-Select-');
$a_sel_cat = array('home' => 'home');
$this->get_child_nav_cat($tmp, 0, $a_sel);
--
public function get_nav_by_parent($parent) {
$all_nav = $this->db
->select('id, title, parent')
->where('parent',$parent)
->order_by('position')
->get('navigation_links')
->result_array();
$a_tmp = array();
foreach($all_nav as $item)
{
if($parent != 0){
$item['title'] = '--' . $item['title'];
}
$a_tmp[] = $item;
}
return $a_tmp;
}
-- Recursive function
public function get_child_nav_cat($a_data, $parent, &$a_sel) {
foreach($a_data as $item) {
$a_sel[$item['page_slug_key']] = $item['title'];
$atmp = $this->get_nav_by_parent($item['id']);
$this->get_child_nav_cat($atmp, $item['id'], $a_sel);
}
return $a_sel;
}
Please give me suggestions for the best solution to display the data as child-parent relationship in select box.
Thanks in advance!
Best way to display parent child relationship is mentain parent and child flag in Database instead of
fetching value using loop.
In your case Home, Home 1 is parent flag and menus belong on child flag.
fetch data from db and your loop look like this:-
$arr = array(0 => array('name' => 'home','parent' => 0),
1 => array('name' => 'menu 1 ','parent' => 1),
2 => array('name' => 'menu 2 ','parent' => 1),
3 => array('name' => 'home 1','parent' => 0),
4 => array('name' => 'menu 3 ','parent' => 2),
5 => array('name' => 'menu 4','parent' => 2)
);
$dd_html = '<select>';
foreach($arr as $k => $v){
if($v['parent'] == 0 )
$dd_html .='<option>'.$v['name'].'</option>';
else
$dd_html .='<option>--'.$v['name'].'</option>';
}
$dd_html .= '</select>';
echo $dd_html;
Output :-
home
-menu 1
-menu 2
home 1
-menu 3
-menu 4
Set ParentID=0 for detecting root item
then execute this:
SELECT * FROM table ORDER BY ParentID, ID
Then iterate through result and when ParentID changed, create new level.

How to reorder this array?

I have a database table as follows:
This returns all column titles in the pic, but the one's that are most important are slug, and parent (not sure about id_button).
The array gets ordered automatically by id_button ASC, which really irks me. But, anyways, this is not important, as I need to order it completely different, or re-order it after the array is populated.
The array returns this, by order of id_button:
$new_menu_buttons = array(
0 => array(
'id_button' => 1,
'parent' => 'help',
'position' => 'child_of',
'slug' => 'testing',
),
1 => array(
'id_button' => 2,
'parent' => 'packages',
'position' => 'after',
'slug' => 'sub_test_1',
),
2 => array(
'id_button' => 3,
'parent' => 'google.com',
'position' => 'after',
'slug' => 'another_test',
),
3 => array(
'id_button' => 4,
'parent' => 'testing'
'position' => 'child_of',
'slug' => 'google.com',
)
);
I need to order it so that if a slug is found within any parent, than the slug that is in the parent needs to be loaded before the one that has it defined within the parent.
Its not important if it is directly before it. For example, you see testing is the first slug that gets returned, and yet the parent for this is the last slug (google.com). So as long as the slug row where the parent is defined gets ordered so that it is BEFORE the row that has the slug value in the parent column, everything is fine.
So in this situation, it can be reordered as any of these 3 ordered arrays below:
$new_menu_buttons = array(
0 => array(
'id_button' => 1,
'parent' => 'help',
'position' => 'child_of',
'slug' => 'testing',
),
1 => array(
'id_button' => 2,
'parent' => 'packages',
'position' => 'after',
'slug' => 'sub_test_1',
),
2 => array(
'id_button' => 4,
'parent' => 'testing',
'position' => 'child_of',
'slug' => 'google.com',
),
3 => array(
'id_button' => 3,
'parent' => 'google.com'
'position' => 'after',
'slug' => 'another_test',
)
);
OR this...
$new_menu_buttons = array(
0 => array(
'id_button' => 1,
'parent' => 'help',
'position' => 'child_of',
'slug' => 'testing',
),
1 => array(
'id_button' => 4,
'parent' => 'testing',
'position' => 'child_of',
'slug' => 'google.com',
),
2 => array(
'id_button' => 2,
'parent' => 'packages',
'position' => 'after',
'slug' => 'sub_test_1',
),
3 => array(
'id_button' => 3,
'parent' => 'google.com'
'position' => 'after',
'slug' => 'another_test',
)
);
OR even this...
$new_menu_buttons = array(
0 => array(
'id_button' => 1,
'parent' => 'help',
'position' => 'child_of',
'slug' => 'testing',
),
1 => array(
'id_button' => 4,
'parent' => 'testing',
'position' => 'child_of',
'slug' => 'google.com',
),
2 => array(
'id_button' => 3,
'parent' => 'google.com'
'position' => 'after',
'slug' => 'another_test',
),
3 => array(
'id_button' => 2,
'parent' => 'packages',
'position' => 'after',
'slug' => 'sub_test_1',
)
);
All 3 of these ordered arrays will work because the array with the slug that matches the parent is before the array with the matching parent, and since the slug value, sub_test_1 doesn't match any of the parent values this array order is unimportant, so that array can be located anywhere within the array.
How can I do this? I'm thinking of just looping through the array somehow and trying to determine if the slug is in any of the parents, and just do a reordering somehow...
In short, the slug needs to be ordered before the parent ONLY if there is a parent that matches a slug within the array. Otherwise, if no match is found, the order isn't important.
As Niko suggested, databases support powerful sorting functionality, so you normally can best solve this by telling the database in which order to return the data. If the data is queried with SQL, that's the ORDER BY clause. This is specified in the documentation of your database, assuming you're using MySQL 5.0: http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html
If you can not influence the order on the database level, you're in the need to sort the array in PHP. You actually have an array of arrays, in which the outer array is just a list having the id (primary key) of each row and the other fields as a fieldname -> value array as a value (inner array).
Your sort is *user-defined` - you specify the sort order. A common way is to have a sort function that compares two entries which each other. That sort function needs to decide which of those two is of a higher sort-order than the other (or both have the same weight). In you case one item is higher than the other if one is the child of the other.
That's the general principle. You define the sort function that decides (the so called callback function), and PHP takes care to feed it with the array data to sort with the usortDocs function.
A sub-problem you need to solve then is to decide whether or not a child exists in the whole array (an item with a slug having the same value as parent). As this all looks like it can be a bit more complex, it's wise to encapsulate this all into a class of it's own.
Example / Demo:
class menuButtons
{
/**
* #var array
*/
private $buttons;
public function __construct(array $buttons)
{
$this->buttons = $buttons;
}
public function sortChildsFirst()
{
$buttons = $this->buttons;
usort($buttons, array($this, 'sortCallback'));
return $buttons;
}
private function sortCallback($a, $b)
{
// an element is more than any other if it's parent
// value is any other slugs value
if ($this->slugExists($a['parent']))
return 1;
return -1;
}
private function slugExists($slug)
{
foreach($this->buttons as $button)
{
if ($button['slug'] === $slug)
return true;
}
return false;
}
}
$buttons = new menuButtons($new_menu_buttons);
$order = $buttons->sortChildsFirst();
Note: This code is exploiting the fact that your sort order is only roughly specified. You only wrote that you need to have children before parents, so if you take all children first, this will always be the case. It's not that each parent will directly follow the child.
Nevertheless, this skeleton class can work as a base to further improve the search functionality as it's fully encapsulated. You can even change the whole sort method, e.g. to completely write one of your own even w/o usort, like outlined below. The main code does not need to change as it's only making use of the sortChildsFirst method.
You can sort an array once populated using the usort() function.
http://php.net/manual/en/function.usort.php
Since your structure is tree-alike, the first thing that comes to mind is to build a tree out of it. It goes like this:
$tree = array();
foreach($array as $e) {
$p = $e['parent'];
$s = $e['slug'];
if(!isset($tree[$p]))
$tree[$p] = new stdclass;
if(!isset($tree[$s]))
$tree[$s] = new stdclass;
$tree[$s]->data = $e;
$tree[$p]->sub[] = $tree[$s];
}
This creates a set of objects, with the members data and sub = list of child objects.
Now we iterate the tree and for each "root" node, add it and its children to the sorted array:
$out = array();
foreach($tree as $node)
if(!isset($tree[$node->data['parent']]))
add($out, $node);
where add() is
function add(&$out, $node) {
if(isset($node->data))
$out[] = $node->data;
if(isset($node->sub))
foreach($node->sub as $n)
add($out, $n);
}
hope this helps.
Ok, first let me thank you all for your detailed explanations. They are very intuitive. However, I found another way, can you guys let me know if you spot anything wrong with this method here please?
Click here to see a Demo of this working!
$temp_buttons = array();
foreach($new_menu_buttons as $buttons)
$temp_buttons[$buttons['parent']] = $buttons['slug'];
dp_sortArray($new_menu_buttons, $temp_buttons, 'slug');
// The $new_menu_buttons array is now sorted correctly! Let's check it...
var_dump($new_menu_buttons);
function dp_sortArray(&$new_menu_buttons, $sortArray, $sort)
{
$new_array = array();
$temp = array();
foreach ($new_menu_buttons as $key => $menuitem)
{
if (isset($sortArray[$menuitem[$sort]]))
{
$new_array[] = $menuitem;
$temp[$menuitem['parent']] = $menuitem['slug'];
unset($new_menu_buttons[$key]);
}
}
$ordered = array();
if (!empty($new_array))
{
foreach ($new_array as $key => $menuitem)
{
if (isset($temp[$menuitem[$sort]]))
{
$ordered[] = $menuitem;
unset($new_array[$key]);
}
}
}
else
{
$new_menu_buttons = $new_menu_buttons;
return;
}
$new_menu_buttons = array_merge($ordered, $new_array, $new_menu_buttons);
}
Seems to work in all instances that I tested, but ofcourse, their could be a flaw in it somewhere. What do you all think of this?

Categories