php tree sitemap algorithm with no rucursion - php

I want to make a sitemap generator and the generated sitemap must be be like a tree.Can someone point me to an algorithm that does this? Or does anyone know the algorithm?
The structure of the sitemap should look like something like this :
I was thinking to use arrays to do this but i can't think of an algorithm to get all links from the website and build the arrays.

I came up with
<?php
$links = array('bla.com/bla1/bla2', 'bla.com/bla1', 'bla.com/bla1/bla3', 'bla.com', 'bla.com/blabla/bla1/bla4', 'bla.com/blabla/otherbla/onemorebla');
$links = array_fill_keys($links, 0);
foreach($links as $key => $value){
$levelsNumber = count(explode('/', $key));
$links[$key] = $levelsNumber;
}
$output = array();
$maxLevel = 1;
foreach ($links as $link => $levels){
if ($levels > $maxLevel) $maxLevel = $levels;
}
for($level = 1; $level <= $maxLevel; $level++){
foreach ($links as $link => $levels){
$parts = explode('/', $link);
if (count($parts) >= $level){
$levelExists = false;
if (!$levelExists){
$keysString = '';
for ($j = 0; $j < $level; $j++){
$keysString .= "['".$parts[$j]."']";
}
eval('$output'.$keysString.'= NULL;');
$levelExists = true;
}
}
}
}
print_r($output);
?>
running it gives
Array
(
[bla.com] => Array
(
[bla1] => Array
(
[bla2] =>
[bla3] =>
)
[blabla] => Array
(
[bla1] => Array
(
[bla4] =>
)
[otherbla] => Array
(
[onemorebla] =>
)
)
)
)
I think if you play with it you might get what you've expected.

Related

Building an associative array using for loop in php

I am trying to create an associative array using php. My desired output is
Array
(
[key] => fl_0_sq
),
Array
(
[key] => fl_1_sq
)
The code is
$max_val = 2;
for($i=0; $i<$max_val; $i++)
{
$flr_arr .= "array('key' => 'fl_".$i."_sq'),";
}
print_r($flr_arr);
Output is
array('key' => 'fl_0_sq'),array('key' => 'fl_1_sq'),
Now the issue is that it has become a string instead of an array. Is it at all possible to create a array structure like the desired output. Any help is highly appreciated.
You could do this:
<?php
$flr_arr = [];
$max_val = 2;
for ($i = 0; $i < $max_val; $i++) {
$flr_arr[][key] = 'fl_' . $i . '_sq';
}
$output = "<pre>";
foreach ($flr_arr as $i => $flr_arr_item) {
$output .= print_r($flr_arr_item, true);
if($i < count($flr_arr)-1){
$output = substr($output, 0, -1) . ",\n";
}
}
$output .= "</pre>";
echo $output;
The output:
Array
(
[key] => fl_0_sq
),
Array
(
[key] => fl_1_sq
)
I'm not exactly sure what you want to do, but your output could be done by this:
$max_val = 2;
for($i=0; $i<$max_val; $i++)
{
$flr_arr = [];
$flr_arr['key'] = 'fl_".$i."_sq';
print_r($flr_arr);
}
You're declaring a string and concatenating it. You want to add elements to an array. You also can't create multiple arrays with the same name. What you can do, though is a 2D array:
$flr_arr[] = array("key"=>"fl_$i_sq");
Note the lack of quotes around array(). The "[]" syntax adds a new element to the end of the array. The output would be -
array(array('key' => 'fl_0_sq'),array('key' => 'fl_1_sq'))

Dynamically creating a multidimensional array based on paths

So I've got a list of paths, such as:
path/to/directory/file1
path/directory/file2
path2/dir/file3
path2/dir/file4
And I'd like to convert them into a multidimensional array like this:
array(
path => array(
to => array(
directory => array(
file1 => someValue
),
),
directory => array(
file2 => someValue
),
),
path2 => array(
dir => array(
file3 => someValue,
file4 => someValue
)
)
)
My first thought was to explode() the paths into segments and set up the array using a foreach loop, something like this:
$arr = array();
foreach ( $path as $p ) {
$segments = explode('/', $p);
$str = '';
foreach ( $segments as $s ) {
$str .= "[$s]";
}
$arr{$str} = $someValue;
}
But this doesn't work, and since the number of segments varies, I've kinda got stumped. Is there away to do this?
If somevalue can be an empty array:
<?php
$result = array();
$input = [
'path/to/directory/file1',
'path/directory/file2',
'path2/dir/file3',
'path2/dir/file4',
];
foreach( $input as $e ) {
nest( $result, explode('/', $e));
}
var_export($result);
function nest(array &$target, array $parts) {
if ( empty($parts) ) {
return;
}
else {
$e = array_shift($parts);
if ( !isset($target[$e]) ) {
$target[$e] = [];
}
nest($target[$e], $parts);
}
}
Here is the solution and a easy way
Just Reverse the whole exploded array and start creating array within a Array
$path[1] = "path/to/directory/file1";
$path[2] = "path/directory/file2";
$path[3] = "path2/dir/file3";
$path[4] = "path2/dir/file4";
$arr = array();
$b = array();
$k = 0;
foreach($path as $p) {
$c = 0;
$segments = explode('/', $p);
$reversed = array_reverse($segments);
foreach($reversed as $s) {
if ($c == 0) {
$g[$k] = array($s => "somevalue");
} else {
$g[$k] = array($s => $g[$k]);
}
$c++;
}
$k++;
}
var_dump($g);
Thanks so much VolkerK! Your answer didn't quite answer my question but it got me on the right track. Here's the version I ended up using to get it to work:
$result = array();
$input = [
'path/to/directory/file1' => 'someValue',
'path/directory/file2' => 'someValue',
'path2/dir/file3' => 'someValue',
'path2/dir/file4' => 'someValue',
];
foreach( $input as $e=>$val ) {
nest( $result, explode('/', $e), $val);
}
var_export($result);
function nest(array &$target, array $parts, $leafValue) {
$e = array_shift($parts);
if ( empty($parts) ) {
$target[$e] = $leafValue;
return;
}
if ( !isset($target[$e]) ) {
$target[$e] = [];
}
nest($target[$e], $parts, $leafValue);
}
I basically just added the somevalue as $leafValue and moved the base case around so that it would add the leafValue instead of a blank array at the end.
This results in:
Array
(
[path] => Array
(
[to] => Array
(
[directory] => Array
(
[file1] => someValue
)
)
[directory] => Array
(
[file2] => someValue
)
)
[path2] => Array
(
[dir] => Array
(
[file3] => someValue
[file4] => someValue
)
)
)
Thanks a lot!
It can be done without recursion
$path = array(
'path/to/directory/file1',
'path/directory/file2',
'path2/dir/file3',
'path2/dir/file4');
$arr = [];
$someValue = 'someValue';
foreach ( $path as $p ) {
$segments = explode('/', $p);
$str = '';
$p = &$arr;
foreach ( $segments as $s ) {
if (! isset($p[$s] ) ) $p[$s] = array();
$p = &$p[$s];
}
$p = $someValue;
}
print_r($arr);

How to extract array Keys to String in an array PHP

I need to extract a associative array keys into a string and implode with "/" or any character/symbols.
For eg:
$array = array([key1] =>
array([key11] =>
array([key111] => 'value111',
[key112] => 'value112',
[key113] => 'value113',
),
),
);
I need an output as below array:
array([0] => 'key1/key11/key111',[1] => 'key1/key11/key112', [2] => 'key1/key11/key112');
I've edited an answer given here and came up with the following code.
function listArrayRecursive($someArray, &$outputArray, $separator = "/") {
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($someArray), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $k => $v) {
if (!$iterator->hasChildren()) {
for ($p = array(), $i = 0, $z = $iterator->getDepth(); $i <= $z; $i++) {
$p[] = $iterator->getSubIterator($i)->key();
}
$path = implode($separator, $p);
$outputArray[] = $path;
}
}
}
$outputArray = array();
listArrayRecursive($array, $outputArray);
print_r($outputArray);
Input:
Array
(
[key1] => Array
(
[key11] => Array
(
[key111] => value111
[key112] => value113
[key113] => value113
)
)
)
Output:
Array
(
[0] => key1/key11/key111
[1] => key1/key11/key112
[2] => key1/key11/key113
)
Works for different depth of array:
function getKeys($array, $prefix='', $separator = '/') {
$return = array();
foreach($array as $key => $value) {
if (!is_array($value)) $return[] = $prefix . $key;
else $return = array_merge($return, getKeys($value, $prefix . $key . separator), $separator);
}
return $return;
}
$keys = getKeys($array, '', '#');
See online fiddle http://ideone.com/krU4Xn
you could do something like...
$mapArray = array();
$symbol = '/';
foreach($array as $k =>$v)
foreach($v as $k1 =>$v1)
foreach($v1 as $k2 =>$v2)
$mapArray[] = $k.$symbol.$k1.$symbol.$k2;
also this obviously only works in this particular case, if it needs to be more generic it can be done, but I think this should get you started.

PHP: Count the appearance of particular value in array

I am wondering if I could explain this.
I have a multidimensional array , I would like to get the count of particular value appearing in that array
Below I am showing the snippet of array . I am just checking with the profile_type .
So I am trying to display the count of profile_type in the array
EDIT
Sorry I've forgot mention something, not something its the main thing , I need the count of profile_type==p
Array
(
[0] => Array
(
[Driver] => Array
(
[id] => 4
[profile_type] => p
[birthyear] => 1978
[is_elite] => 0
)
)
[1] => Array
(
[Driver] => Array
(
[id] => 4
[profile_type] => d
[birthyear] => 1972
[is_elite] => 1
)
)
)
Easy solution with RecursiveArrayIterator, so you don't have to care about the dimensions:
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$counter = 0
foreach ($iterator as $key => $value) {
if ($key == 'profile_type' && $value == 'p') {
$counter++;
}
}
echo $counter;
Something like this might work...
$counts = array();
foreach ($array as $key=>$val) {
foreach ($innerArray as $driver=>$arr) {
$counts[] = $arr['profile_type'];
}
}
$solution = array_count_values($counts);
I'd do something like:
$profile = array();
foreach($array as $elem) {
if (isset($elem['Driver']['profile_type'])) {
$profile[$elem['Driver']['profile_type']]++;
} else {
$profile[$elem['Driver']['profile_type']] = 1;
}
}
print_r($profile);
You may also use array_walk($array,"test") and define a function "test" that checks each item of the array for 'type' and calls recursively array_walk($arrayElement,"test") for items of type 'array' , else checks for the condition. If condition satisfies, increment a count.
Hi You can get count of profuke_type==p from a multi dimensiona array
$arr = array();
$arr[0]['Driver']['id'] = 4;
$arr[0]['Driver']['profile_type'] = 'p';
$arr[0]['Driver']['birthyear'] = 1978;
$arr[0]['Driver']['is_elite'] = 0;
$arr[1]['Driver']['id'] = 4;
$arr[1]['Driver']['profile_type'] = 'd';
$arr[1]['Driver']['birthyear'] = 1972;
$arr[1]['Driver']['is_elite'] = 1;
$arr[2]['profile_type'] = 'p';
$result = 0;
get_count($arr, 'profile_type', 'd' , $result);
echo $result;
function get_count($array, $key, $value , &$result){
if(!is_array($array)){
return;
}
if($array[$key] == $value){
$result++;
}
foreach($array AS $arr){
get_count($arr, $key, $value , $result);
}
}
try this..
thanks

most efficient method of turning multiple 1D arrays into columns of a 2D array

As I was writing a for loop earlier today, I thought that there must be a neater way of doing this... so I figured I'd ask. I looked briefly for a duplicate question but didn't see anything obvious.
The Problem:
Given N arrays of length M, turn them into a M-row by N-column 2D array
Example:
$id = [1,5,2,8,6]
$name = [a,b,c,d,e]
$result = [[1,a],
[5,b],
[2,c],
[8,d],
[6,e]]
My Solution:
Pretty straight forward and probably not optimal, but it does work:
<?php
// $row is returned from a DB query
// $row['<var>'] is a comma separated string of values
$categories = array();
$ids = explode(",", $row['ids']);
$names = explode(",", $row['names']);
$titles = explode(",", $row['titles']);
for($i = 0; $i < count($ids); $i++) {
$categories[] = array("id" => $ids[$i],
"name" => $names[$i],
"title" => $titles[$i]);
}
?>
note: I didn't put the name => value bit in the spec, but it'd be awesome if there was some way to keep that as well.
Maybe this? Not sure if it's more efficient but it's definitely cleaner.
/*
Using the below data:
$row['ids'] = '1,2,3';
$row['names'] = 'a,b,c';
$row['titles'] = 'title1,title2,title3';
*/
$categories = array_map(NULL,
explode(',', $row['ids']),
explode(',', $row['names']),
explode(',', $row['titles'])
);
// If you must retain keys then use instead:
$withKeys = array();
foreach ($row as $k => $v) {
$v = explode(',', $v);
foreach ($v as $k2 => $v2) {
$withKeys[$k2][$k] = $v[$k2];
}
}
print_r($categories);
print_r($withKeys);
/*
$categories:
array
0 =>
array
0 => int 1
1 => string 'a' (length=1)
2 => string 'title1' (length=6)
...
$withKeys:
array
0 =>
array
'ids' => int 1
'names' => string 'a' (length=1)
'titles' => string 'title1' (length=6)
...
*/
Just did a quick simple benchmark for the 4 results on this page and got the following:
// Using the following data set:
$row = array(
'ids' => '1,2,3,4,5',
'names' => 'abc,def,ghi,jkl,mno',
'titles' => 'pqrs,tuvw,xyzA,BCDE,FGHI'
);
/*
For 10,000 iterations,
Merge, for:
0.52803611755371
Merge, func:
0.94854116439819
Merge, array_map:
0.30260396003723
Merge, foreach:
0.40261697769165
*/
Yup, array_combine()
$result = array_combine( $id, $name );
EDIT
Here's how I'd handle your data transformation
function convertRow( $row )
{
$length = null;
$keys = array();
foreach ( $row as $key => $value )
{
$row[$key] = explode( ',', $value );
if ( !is_null( $length ) && $length != count( $row[$key] ) )
{
throw new Exception( 'Lengths don not match' );
}
$length = count( $row[$key] );
// Cheap way to produce a singular - might break on some words
$keys[$key] = preg_replace( "/s$/", '', $key );
}
$output = array();
for ( $i = 0; $i < $length; $i++ )
{
foreach ( $keys as $key => $singular )
{
$output[$i][$singular] = $row[$key][$i];
}
}
return $output;
}
And a test
$row = convertRow( $row );
echo '<pre>';
print_r( $row );

Categories