PHP: reorder array to show hierarchy - php

How can I turn the first array in to the second one? The goal is to create an array that shows the hierarchy, based on location_id and parent_id. Each location_name should be in an array of which the key is its parent_id.
Ignore the values I gave to location_name. No value for parent_id == NULL, these are the top level items.
First array:
Array
(
[0] => stdClass Object
(
[location_id] => 1
[location_name] => Town 1
[parent_id] =>
)
[1] => stdClass Object
(
[location_id] => 2
[location_name] => Town 1.1
[parent_id] =>
)
[2] => stdClass Object
(
[location_id] => 3
[location_name] => Town 1.2
[parent_id] => 1
)
[3] => stdClass Object
(
[location_id] => 4
[location_name] => Town 1.3
[parent_id] => 1
)
[4] => stdClass Object
(
[location_id] => 5
[location_name] => town 1.1.1
[parent_id] => 2
)
[5] => stdClass Object
(
[location_id] => 6
[location_name] => Town 1.1.2
[parent_id] => 3
)
);
Resulting array should be:
Array(
'Town 1' = array(
'town 1.2',
'town 1.3' = array(
'town 1.1.2'
)
),
'Town 2' = array(
'town 1.1.1'
)
);
EDIT: working solution based on Rijk's answer
function _order_locs($parent, $array)
{
$return = array();
foreach ( $array as $town )
{
if ( $town->parent_id == $parent )
{
$set = $this->_order_locs( $town->location_id, $array );
if( $this->_menu_is_parent($town->location_id, $array) ) $return[$town->location_name] = $set;
else $return[] = $town->location_name;
}
}
return $return;
}
function _menu_is_parent($id, $array)
{
foreach( $array as $a )
{
if( $a->parent_id == $id ) return TRUE;
}
}

You have to loop through it, using a recursive function (one that calls itself):
function getChilds( $parent, $array ) {
$return = array();
foreach ( $array as $town ) {
if ( $town['location_id'] == $parent ) {
$return[] = array(
'name' => $town['location_name'],
'childs' => getChilds( $town['location_id'], $array )
);
}
}
return $return;
}
$towns_tree = getChilds( 0, $towns );
Might not work right off the bat, but that gives you a nice oppurtunity to play with the code and get familiar with this concept ;)

Here is some code that will more or less do what you need. You will have to tweak it to your liking.
<?php
Class Node {
public $id;
public $parent_id;
public $value;
public $children;
public $depth;
function __construct($id, $parent_id, $value) {
$this->id = $id;
$this->parent_id = $parent_id;
$this->value = $value;
$this->children = array();
$this->depth = 0;
}
function add_child(Node $new_child) {
if ($new_child->parent_id == $this->id) {
$this->children[$new_child->id] = $new_child;
$this->children[$new_child->id]->depth = $this->depth + 1;
} else {
foreach ($this->children as $child) {
$child->add_child($new_child);
}
}
}
function to_array() {
if (count($this->children) > 0) {
$arr = array();
foreach ($this->children as $child) {
array_push($arr, $child->to_array());
}
return array($this->value => $arr);
} else {
return $this->value;
}
}
function str() {
echo str_repeat(" ", $this->depth) . $this->value . "\n";
foreach ($this->children as $child) {
$child->str();
}
}
}
?>
Here is some sample code to test it with:
<?php
$arr = Array(
array('location_id' => 1,
'location_name' => 'Town 1',
'parent_id' => 0),
array('location_id' => 2,
'location_name' => 'Town 1.1',
'parent_id' => 0),
array('location_id' => 3,
'location_name' => 'Town 1.2',
'parent_id' => 1),
array('location_id' => 4,
'location_name' => 'Town 1.3',
'parent_id' => 1),
array('location_id' => 5,
'location_name' => 'Town 1.1.1',
'parent_id' => 2),
array('location_id' => 6,
'location_name' => 'Town 1.1.2',
'parent_id' => 3)
);
$root = new Node(0, 0, 'root');
foreach ($arr as $item) {
$node = new Node($item['location_id'],
$item['parent_id'],
$item['location_name']);
$root->add_child($node);
}
$tree = $root->to_array();
$tree = $tree['root'];
var_dump($tree);
?>

Related

Where to pass temp array when using recursive function?

I'm using a foreach loop inside my recursive function. But I have trouble figuring out where to pass my return statement. I need to return my temp array at some point, but I'm not sure how to do this:
<?php
$patterns = function($array, $temp = array(), $i = 0, $id = 0, $parent = 0) use(&$patterns) {
$return = null;
if(array_key_exists($i, $array)) {
foreach($array[$i] as $set) {
if($parent == $set['id']) {
$data = array(
'id' => $set['id'],
'parent' => $set['parent']
);
array_push($temp, $data);
}
$patterns($array, $temp, $i + 1, $set['id'], $set['parent']);
}
}
};
print_r($patterns($rev_relations));
?>
This is my data:
Array(
[0] => Array(
[0] => Array(
[id] => 60
[parent] => 55
)
[1] => Array(
[id] => 57
[parent] => 54
)
)
[1] => Array(
[0] => Array(
[id] => 61
[parent] => 50
)
[1] => Array(
[id] => 54
[parent] => 49
)
)
[2] => Array(
[0] => Array(
[id] => 49
[parent] => 0
)
)
)
<?php
//pass $temp by reference so outside variable gets populated
$patterns = function($array, &$temp, $i = 0, $id = 0, $parent = 0) use(&$patterns) {
$return = null;
if(array_key_exists($i, $array)) {
foreach($array[$i] as $set) {
if($parent == $set['id']) {
$data = array(
'id' => $set['id'],
'parent' => $set['parent']
);
array_push($temp, $data);
}
$patterns($array, $temp, $i + 1, $set['id'], $set['parent']);
}
}
};
//actuall array is created on temp here
$temp=array();
$patterns($rev_relations,$temp);
?>
wont this work? Never really worked with nameless functions, but this is how i would go about it on a normall recursive function
Ok, take two
<?php
$patterns = function($array, $temp = array(), $i = 0, $id = 0, $parent = 0) use(&$patterns) {
$return = null;
if(array_key_exists($i, $array)) {
foreach($array[$i] as $set) {
if($parent == $set['id']) {
$data = array(
'id' => $set['id'],
'parent' => $set['parent']
);
array_push($temp, $data);
}
return $patterns($array, $temp, $i + 1, $set['id'], $set['parent']);
}
}
else
{
return $temp;
}
};
$patterns($rev_relations);
?>

php tree ul li hierarchy menu from array

we have this array from mysqli query output :
$items = Array
(
Array
(
'id' => 1,
'title' => 'menu1',
'parent_id' => 0
),
Array
(
'id' => 2,
'title' => 'submenu1-1',
'parent_id' => 1
),
Array
(
'id' => 3,
'title' => 'submenu1-2',
'parent_id' => 1
),
Array
(
'id' => 4,
'title' => 'menu2',
'parent_id' => 0
),
Array
(
'id' => 5,
'title' => 'submenu2-1',
'parent_id' => 4
)
);
and we need this html output with php :
<ul>
<li><a>menu1</a>
<ul>
<li><a>submenu1-1</a></li>
<li><a>submenu1-2</a></li>
</ul>
</li>
<li><a>menu2</a>
<ul>
<li><a>submenu2-1</a></li>
</ul>
</li>
</ul>
can anyone help me ?
Probably this is very easy but I have tried everything already without success !!
finally i found answer like this:
function generateTreeMenu($datas, $parent = 0, $limit=0){
if($limit > 1000) return '';
$tree = '';
$tree = '<ul>';
for($i=0, $ni=count($datas); $i < $ni; $i++){
if($datas[$i]['parent_id'] == $parent){
$tree .= '<li><a>';
$tree .= $datas[$i]['title'].'</a>';
$tree .= generatePageTree($datas, $datas[$i]['id'], $limit++);
$tree .= '</li>';
}
}
$tree .= '</ul>';
return $tree;
}
echo generateTreeMenu($items);
//index elements by id
foreach ($items as $item) {
$item['subs'] = array();
$indexedItems[$item['id']] = (object) $item;
}
//assign to parent
$topLevel = array();
foreach ($indexedItems as $item) {
if ($item->parent_id == 0) {
$topLevel[] = $item;
} else {
$indexedItems[$item->parent_id]->subs[] = $item;
}
}
//recursive function
function renderMenu($items) {
$render = '<ul>';
foreach ($items as $item) {
$render .= '<li>' . $item->title;
if (!empty($item->subs)) {
$render .= renderMenu($item->subs);
}
$render .= '</li>';
}
return $render . '</ul>';
}
echo renderMenu($topLevel);
The problem here is just the structure of the array, so first you can convert the array to a more suitable structure, then you can draw your list easily.
Here is a function to convert the array:
function makeTree( $rst, $level, &$tree )
{
for ( $i=0, $n=count($rst); $i < $n; $i++ )
{
if ( $rst[$i]['parent_id'] == $level )
{
$branch = array(
'id' => $rst[$i]['id'],
'title' => $rst[$i]['title'],
'children' => array()
);
makeTree( $rst, $rst[$i]['id'], $branch['children'] );
$tree[] = $branch;
}
}
}
Mode of use:
$tree = array();
makeTree( $originalArray, 0, $tree );
At the end, you will have a new array in $tree structured as shown below, which you can easily draw in your view.
Array
(
[0] => Array
(
[id] => 1
[title] => menu1
[children] => Array
(
[0] => Array
(
[id] => 2
[title] => submenu1-1
[children] => Array
(
)
)
[1] => Array
(
[id] => 3
[title] => submenu1-2
[children] => Array
(
)
)
)
)
[1] => Array
(
[id] => 4
[title] => menu2
[children] => Array
(
[0] => Array
(
[id] => 5
[title] => submenu2-1
[children] => Array
(
)
)
)
)
)
Try this
$node = array();
foreach ($items as $item) {
if ($item['parent_id'] == 0) {
$node[$item['id']][$item['id']] = $item['title'];
} else {
$node[$item['parent_id']][$item['id']] = $item['title'];
}
}
$result = array();
foreach ($node as $key => $value) {
$result[$value[$key]] = array_diff($value, array($key => $value[$key]));
}

PHP Counting inside an Array

I want to create a list where if its already in the array to add to the value +1.
Current Output
[1] => Array
(
[source] => 397
[value] => 1
)
[2] => Array
(
[source] => 397
[value] => 1
)
[3] => Array
(
[source] => 1314
[value] => 1
)
What I want to Achieve
[1] => Array
(
[source] => 397
[value] => 2
)
[2] => Array
(
[source] => 1314
[value] => 1
)
My current dulled down PHP
foreach ($submissions as $timefix) {
//Start countng
$data = array(
'source' => $timefix['parent']['id'],
'value' => '1'
);
$dataJson[] = $data;
}
print_r($dataJson);
Simply use an associated array:
$dataJson = array();
foreach ($submissions as $timefix) {
$id = $timefix['parent']['id'];
if (!isset($dataJson[$id])) {
$dataJson[$id] = array('source' => $id, 'value' => 1);
} else {
$dataJson[$id]['value']++;
}
}
$dataJson = array_values($dataJson); // reset the keys - you don't nessesarily need this
This is not exactly your desired output, as the array keys are not preserved, but if it suits you, you could use the item ID as the array key. This would simplify your code to the point of not needing to loop through the already available results:
foreach ($submissions as $timefix) {
$id = $timefix['parent']['id'];
if (array_key_exists($id, $dataJson)) {
$dataJson[$id]["value"]++;
} else {
$dataJson[$id] = [
"source" => $id,
"value" => 1
];
}
}
print_r($dataJson);
You should simplify this for yourself. Something like:
<?
$res = Array();
foreach ($original as $item) {
if (!isset($res[$item['source']])) $res[$item['source']] = $item['value'];
else $res[$item['source']] += $item['value'];
}
?>
After this, you will have array $res which will be something like:
Array(
[397] => 2,
[1314] => 1
)
Then, if you really need the format specified, you can use something like:
<?
$final = Array();
foreach ($res as $source=>$value) $final[] = Array(
'source' => $source,
'value' => $value
);
?>
This code will do the counting and produce a $new array as described in your example.
$data = array(
array('source' => 397, 'value' => 1),
array('source' => 397, 'value' => 1),
array('source' => 1314, 'value' => 1),
);
$new = array();
foreach ($data as $item)
{
$source = $item['source'];
if (isset($new[$source]))
$new[$source]['value'] += $item['value'];
else
$new[$source] = $item;
}
$new = array_values($new);
PHP has a function called array_count_values for that. May be you can use it
Example:
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
Output:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)

Filter & sort multidimensional array with multiple values

I have a large multidimensional array something like the below:
Array(
[1] => Array ( [type] => blah1 [category] => cat1 [exp_range] => this_week )
[2] => Array ( [type] => blah1 [category] => cat2 [exp_range] => next week )
[3] => Array ( [type] => blah1 [category] => cat1 [exp_range] => next week )
[4] => Array ( [type] => blah2 [category] => cat2 [exp_range] => this_week )
)
I want to be able to filter this array with multiple filters.
eg. filtering where category = cat1 and type = blah1 would return array 1 and 3.
I have the below function that would return keys 1,2,3 which is incorrect as array 2 doesnt have both cat1 and blah1
Can anyone see what I need to do to get this working?
Also would it be possible to incorporate sortin in this function, if so how?
function array_searcher($needles, $array) {
foreach ($needles as $needle) {
foreach ($array as $key => $value) {
foreach ($value as $v) {
if ($v == $needle) {
$keys[] = $key;
}
}
}
}
return $keys;
}
I decided to rewrite my answer to accommodate both filtering and sorting. I took a heavily object oriented approach to solving this problem, which I will detail below.
You can see all of this code in action at this ideone.com live demonstration.
The first thing I did was define two interfaces.
interface Filter {
public function filter($item);
}
interface Comparator {
public function compare($a, $b);
}
As their names suggest, Filter is used for filtering, and Comparator is used for comparing.
Next, I defined three concrete classes that implements these interfaces, and accomplish what I wanted.
First is KeyComparator. This class simply compares the key of one element to the key of another element.
class KeyComparator implements Comparator {
protected $direction;
protected $transform;
protected $key;
public function __construct($key, $direction = SortDirection::Ascending, $transform = null) {
$this->key = $key;
$this->direction = $direction;
$this->transform = $transform;
}
public function compare($a, $b) {
$a = $a[$this->key];
$b = $b[$this->key];
if ($this->transform) {
$a = $this->transform($a);
$b = $this->transform($b);
}
return $a === $b ? 0 : (($a > $b ? 1 : -1) * $this->direction);
}
}
You can specify a sort direction, as well as a transformation to be done to each element before they are compared. I defined a helped class to encapsulate my SortDirection values.
class SortDirection {
const Ascending = 1;
const Descending = -1;
}
Next, I defined MultipleKeyComparator which takes multiple KeyComparator instances, and uses them to compare two arrays against each other. The order in which they are added to the MultipleKeyComparator is the order of precedence.
class MultipleKeyComparator implements Comparator {
protected $keys;
public function __construct($keys) {
$this->keys = $keys;
}
public function compare($a, $b) {
$result = 0;
foreach ($this->keys as $comparator) {
if ($comparator instanceof KeyComparator) {
$result = $comparator->compare($a, $b);
if ($result !== 0) return $result;
}
}
return $result;
}
}
Finally, I created MultipleKeyValueFilter which is meant to filter an array based on an array of key/value pairs:
class MultipleKeyValueFilter implements Filter {
protected $kvPairs;
public function __construct($kvPairs) {
$this->kvPairs = $kvPairs;
}
public function filter($item) {
$result = true;
foreach ($this->kvPairs as $key => $value) {
if ($item[$key] !== $value)
$result &= false;
}
return $result;
}
}
Now, given the input array (Notice I rearranged them a bit to make the sorting obvious):
$array = array (
'1' => array ('type' => 'blah2', 'category' => 'cat2', 'exp_range' => 'this_week' ),
'2' => array ('type' => 'blah1', 'category' => 'cat1', 'exp_range' => 'this_week' ),
'3' => array ('type' => 'blah1', 'category' => 'cat2', 'exp_range' => 'next_week' ),
'4' => array ('type' => 'blah1', 'category' => 'cat1', 'exp_range' => 'next_week' )
);
Sorting can be achieved by doing the following:
$comparator = new MultipleKeyComparator(array(
new KeyComparator('type'),
new KeyComparator('exp_range')
));
usort($array, array($comparator, 'compare'));
echo "Sorted by multiple fields\n";
print_r($array);
Filtering can be achieved by doing the following:
$filter = new MultipleKeyValueFilter(array(
'type' => 'blah1'
));
echo "Filtered by multiple fields\n";
print_r(array_filter($array, array($filter, 'filter')));
At this point I've given you a great deal of code. I'd suggest that your next step is to combine these two pieces into a single class. This single class would then apply both filtering and sorting together.
Do it:
$arr = array(
1 => array ( "type" => "blah1", "category" => "cat1", "exp_range" => "this_week" ),
2 => array ( "type" => "blah1", "category" => "cat2", "exp_range" => "next week" ),
3 => array ( "type" => "blah1", "category" => "cat1", "exp_range" => "this_week" ),
4 => array ( "type" => "blah2", "category" => "cat2","exp_range" => "next week" ),
);
function filter(array $arr,array $params){
$out = array();
foreach($arr as $key=>$item){
$diff = array_diff_assoc($item,$params);
if (count($diff)==1) // if count diff == 1 - Ok
$out[$key] = $item;
}
return $out;
}
$out = filter($arr,array("type" => "blah1", "category" => "cat1"));
echo '<pre>';
print_r($out);
echo '</pre>';
// output
Array
(
[1] => Array
(
[type] => blah1
[category] => cat1
[exp_range] => this_week
)
[3] => Array
(
[type] => blah1
[category] => cat1
[exp_range] => this_week
)
)
The issue is the fact that your function will return the key of every array that contains "cat1" or "blah1". You can fix it with array_unique():
function array_searcher($needles, $array) {
foreach ($needles as $needle) {
foreach ($array as $key => $value) {
foreach ($value as $v) {
if ($v == $needle) {
$keys[] = $key;
}
}
}
}
return $keys;
}
$bigarray = array(
array('type' => 'blah1', 'category' => 'cat1', 'exp_range' => 'this_week'),
array('type' => 'blah1', 'category' => 'cat2', 'exp_range' => 'next week'),
array('type' => 'blah1', 'category' => 'cat1', 'exp_range' => 'next week'),
array('type' => 'blah2', 'category' => 'cat2', 'exp_range' => 'this_week')
);
$result = array_searcher(array('cat1','blah1'), $bigarray);
$unique_result = array_unique($result);
print_r($unique_result);
so lets assign your base array to a variable:
$array = Array(
[1] => Array ( [type] => blah1 [category] => cat1 [exp_range] => this_week )
[2] => Array ( [type] => blah1 [category] => cat2 [exp_range] => next week )
[3] => Array ( [type] => blah1 [category] => cat1 [exp_range] => next week )
[4] => Array ( [type] => blah2 [category] => cat2 [exp_range] => this_week )
)
and lets's have an array containing our filter:
$filter = array(
'type' => 'blah1'
'category' => 'cat1'
)
then we start our filtering script
foreach ($array as $key => $row){
$i = 0;
foreach ($filter as $filterKey => $filterValue){
if ($row[$filterKey] != $filterValue){
$i++;
}}
if ($i == 0){
$filteredArray[] = $row;
}}
if $i still equals 0 after the row is tested against our filter, we add the row to our filtered array
I vaguely remember implementing this type of functionality many years ago:
http://forums.devnetwork.net/viewtopic.php?t=47855
Look to the sortRows() and _quickSort() methods
HTH

Compare array php foreach loop

I have 2 arrays and i want to create an output array.
Example array requirements for Title and Subtitle field:
Array
(
[title] => Array
(
[required] => 1
[minLength] => 2
[maxLength] => 50
)
[subtitle] => Array
(
[required] => 1
[minLength] => 2
[maxLength] => 55
)
)
Post array after post s:
Array
(
[title] =>
[subtitle] => s
)
Example Output array:
Array
(
[title] => Array
(
[0] => this field is required
[1] => must be longer than 2
)
[subtitle] => Array
(
[0] => must be longer than 2
)
)
How can i generate such array by a foreach loop?
This is what i have, but it wont work well. If i leave title blank and subtitle 1 character he gives back 2 times this field is required. It looks like he duplicated.
class Forms_FormValidationFields {
private $_required;
private $_minLength;
private $_maxLength;
private $_alphaNumeric;
public $_errors;
public function __construct($validate, $posts) {
array_pop($posts);
$posts = array_slice($posts,1);
foreach ( $posts as $postName => $postValue) {
foreach( $validate[$postName] as $key => $ruleValue ){
$set = 'set'.ucfirst($key);
$get = 'get'.ucfirst($key);
$this->$set( $postValue , $ruleValue);
if( $this->$get() != '' || $this->$get() != NULL) {
$test[$postName][] .= $this->$get();
}
}
}
$this->_errors = $test;
}
public function setValidation(){
return $this->_errors;
}
public function getRequired() {
return $this->_required;
}
public function setRequired($value, $ruleValue) {
if (empty($value) && $ruleValue == TRUE) {
$this->_required = 'this field is required';
}
}
public function getMinLength() {
return $this->_minLength;
}
public function setMinLength($value, $ruleValue) {
if (strlen($value) < $ruleValue) {
$this->_minLength = ' must be longer than' . $ruleValue . '';
}
}
public function getMaxLength() {
return $this->_maxLength;
}
public function setMaxLength($value, $ruleValue) {
if (strlen($value) > $ruleValue) {
$this->_maxLength = 'must be shorter than' . $ruleValue . '';
}
}
}
Here you go:
<?php
$required = array(
'This field is not required',
'This field is required'
);
$length = 'Requires more than {less} but less than {more}';
$needs = array(
'title' => array(
'required' => 1,
'minLength' => 2,
'maxLength' => 50,
),
'subtitle' => array(
'required' => 1,
'minLength' => 2,
'maxLength' => 55
)
);
$new_needs = array();
foreach($needs as $key => $value) // Loop over your array
{
$new_needs[$key][] = $required[$value['required']];
$new_needs[$key][] = str_replace(
array('{more}', '{less}'),
array($value['maxLength'], $value['minLength']),
$length
);
}
foreach($_POST as $key => $value)
{
if(empty($value)) { echo $new_needs[$key][0]; }
if(strlen($value) > $needs[$key]['maxLength'] || strlen($value) < $needs[$key]['minLength']) echo $new_needs[$key][1];
}
Should be pretty self explanatory if you read over it.
Result:
Array
(
[title] => Array
(
[0] => This field is required
[1] => Requires more than 2 but less than 50
)
[subtitle] => Array
(
[0] => This field is required
[1] => Requires more than 2 but less than 55
)
)

Categories