Turn string to nested array php - php

I am trying to turn a string into a nested array
Here is my string:
a/b/d.docx
and I wanted to be like this:
array(
"name" => "a",
"type" => "folder",
"sub" => array(
"name" => "b",
"type" => "folder",
"sub" => array(
"name" => "c.docx",
"type" => "file",
"size" => "20"
)
)
)
This is the code that I have so far
$items = explode('/', $strings);
$num = count($items);
$num = --$num;
$temp = array();
foreach($items as $keys => $value) {
$temp[$keys] = array(
"name" => $value,
"type" => "folder",
"items" => $temp[++$keys]
);
if($keys == $num){
$temp[$keys] = array(
"name" => $value,
"type" => "file",
"size" => "20"
);
}
}
var_dump($temp);
I am trying this functions but this only turn string into a single array and it also can't do the 'items' line.
Any help would be appreciated.Thanks.
Note that the path is virtual and doesn't exist.
UPDATE: How can I add path to each array??for example,"path"=>"a/b"

You can do that:
$path = 'a/b/d.docx';
$parts = explode('/', $path);
$result = [ 'name' => array_pop($parts), 'type' => 'file', 'size' => 20 ];
while ($parts) {
$result = [ 'name' => array_pop($parts), 'type' => 'folder', 'sub' => $result ];
}
print_r($result);

<?php
$strings='a/b/d.docx';
$items = explode('/', $strings);
$num = count($items)-1;
$root= array();
$cur = &$root;
$v='';
foreach($items as $keys => $value) {
$v = $v.$value;
$temp = array( "name" => $value, "path"=>$v, "type" => "folder", "items" => "");
if($keys == $num){
$temp = array( "name" => $value, "path"=>$v, "type" => "file", "size" => "20");
}
$v= $v.'/';
if($keys==0) {
$cur = $temp;
}
else
{
$cur['items'] = $temp;
$cur = &$cur['items'];
}
}
var_dump($root);

Try recursion:
public function testAction(){
$sString = 'a/b/c/d.exe';
$aExploded = explode('/', $sString);
var_dump($this->_parse_folder_rec($aExploded));
}
private function _parse_folder_rec($aExploded){
$aResult = [];
$aResult['name'] = array_shift($aExploded);
if($aExploded){
$aResult['type'] = 'folder';
$aResult['sub'] = $this->_parse_folder_rec($aExploded);
}else{
$aResult['type'] = 'file';
$aResult['size'] = 20;
}
return $aResult;
}

Related

Generating hierarchal URL from hierarchal data

I am trying to implement a decision tree based on this jQuery plugin.
It expects data in this format:
$tree = array(
"href" => "/",
"label" => "Title",
"nodes" => array(
array(
"href" => "/q1",
"label" => "Question 1?",
"nodes" => array(
array(
"href" => "/q1/a1",
"label" => "Answer 1",
"nodes" => array(
"href" => "/q1/a1/q11",
"label" => "Question 1.1?",
"nodes" => array(
array(
"href" => "/q1/a1/q11/a11",
"label" => "Answer 1.1",
"nodes" => null
),
array(
"href" => "/q1/a1/q11/a12",
"label" => "Answer 1.1",
"nodes" => null
)
)
)
),
array(
"href" => "/q1/a2",
"label" => "Answer 2",
"nodes" => null
)
)
)
)
);
I fetch the results as a flat list from a database and then am able to generate the tree structure using a recursive function:
function buildTree(array $elements, $rootId = 0, $current_path = '', $new_path = '') {
$ctr = 0;
$branch = array();
foreach($elements as $element) {
if ($element['root_id'] == $rootId) {
$array = array(
'root_id' => $element['root_id'],
'label' => $element['label'],
'text' => $element['text'],
);
if(!empty($current_path)){
$path = $current_path . ++$ctr;
$array['href'] = $path;
}
$new_path = $new_path == '/q' ? '/a' : '/q';
$children = buildTree($elements, $element['id'], $path . $new_path, $new_path);
if ($children) {
$array['nodes'] = $children;
}
$branch[] = $array;
}
}
return $branch;
}
$tree = buildTree($results);
which yields:
$tree = array(
"href" => "/",
"label" => "Title",
"nodes" => array(
array(
"href" => "/q1",
"label" => "Question 1?",
"nodes" => array(
array(
"href" => "/q1/a1",
"label" => "Answer 1",
"nodes" => array(
"href" => "/q1/a1/q1",
"label" => "Question 1.1?",
"nodes" => array(
array(
"href" => "/q1/a1/q1/a1",
"label" => "Answer 1.1",
"nodes" => null
),
array(
"href" => "/q1/a1/q1/a1",
"label" => "Answer 1.1",
"nodes" => null
)
)
)
),
array(
"href" => "/q1/a2",
"label" => "Answer 2",
"nodes" => null
)
)
)
)
);
which gives the correct 'href's up to a depth of 2 but then deviates from the expected format.
I can't figure out how to get the 'href's correct.
How can i generate the correct 'href' using my recursive function as expected by the jQuery plugin?
$path = $current_path . ++$ctr;
You're counting yet this value is localized for that particular function even on recursion. It will never and seems to never move above 1 because after it iterates once, it calls buildTree again.
Is q11 not stored in the database? You need a way of incrementing/parsing/gathering (i am not sure exactly what the value should be) that value to what it should be as it recurses through. Should this value just remove the . from 1.1 ?
Try dropping in this function in place of yours and see if it changes anything:
function buildTree(array $elements, $rootId = 0, $current_path = '', $new_path = '', $parent_id = 0, $ctr = 0) {
$branch = array();
foreach($elements as $element) {
if ($element['root_id'] == $rootId) {
$array = array(
'root_id' => $element['root_id'],
'label' => $element['label'],
'text' => $element['text'],
);
if(!empty($current_path)){
if($parent_id > 0 ) {
$path = $current_path . $parent_id . $ctr;
}else{
$path = $current_path . ++$ctr;
}
$array['href'] = $path;
}
$new_path = $new_path == '/q' ? '/a' : '/q';
$parent_id++;
$children = buildTree($elements, $element['id'], $path . $new_path, $new_path, $parent_id, $ctr);
$parent_id--;
if ($children) {
$array['nodes'] = $children;
}
$branch[] = $array;
}
}
return $branch;
}

How to create dynamic combination with php?

I have 3 array like
$arr = [
"color" => [["name"=>"red"]],
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]]
]
$combo = array();
foreach ($arr['size'] as $size) {
foreach($arr['color'] as $color){
foreach ($arr['type'] as $type) {
$variant = json_encode(['size' => $size->name, 'color' =>
$color->name, 'type' => $type->name]);
array_push($combo,$variant);
}
}
}
echo $combo;
// result
0 => "{"size":"15 inch","color":"yellow","type":"metal"}"
1 => "{"size":"18 inch","color":"yellow","type":"plastic"}"
It works properly but but there is can be less or more variants. How can I handle this.
For example
$arr = [
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]]
]
Or
$arr = [
"color" => [["name"=>"red"]],
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]],
"brand" => [['name' => 'something']],
]
For what i understand, you have to combine the arrays of properties into one array of
object.
I have to leave now, but if you need a explanation leave a comment and i updated the answers
$arr = [
"color" => [["name"=>"red"],['name'=>'yellow']],
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]],
"brand" => [['name' => 'something']],
];
function runFor($arr ,&$array, $keys,$index,&$positions){
foreach ($arr[$keys[$index]] as $key => $espec){
$positions[$keys[$index]] = $key;
if($index + 1 < count($keys)){
runFor($arr,$array,$keys, $index+1,$positions);
}else{
$item = (object)[];
foreach ($keys as $key){
$item->$key = $arr[$key][$positions[$key]]['name'];
}
array_push($array,$item);
}
unset($positions[$keys[$index]]);
}
}
$array = array();
$keys = array_keys($arr);
$positions = [];
runFor($arr,$array,$keys,0,$positions);
$combo = array();
foreach ($array as $item){
array_push($combo,json_encode($item));
}
var_dump($combo);

Convert array keys to a string in PHP

Example Array:
$array = array([key1] =>
array([key11] =>
array([key111] => 'value111',
[key112] => 'value112',
[key113] => 'value113',
[key114] => array(A,B,C,D),
),
),
);
I need an output as below array:
array([key1/key11/key111] => 'value111',
[key1/key11/key112] => 'value112',
[key1/key11/key113] => 'value113',
[key1/key11/key114] => 'A,B,C,D' );
and i have tried using this function,
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);
I cant able to find how to achieve this by using the above function for "key1/key11/key114" getting value as i expected. Please help me on this.
Input:
$array = array(
'key1' => array(
'key11' => array(
'key111' => 'value111',
'key112' => 'value112',
'key113' => 'value113',
'key114' => array('A','B','C','D'),
),
'key12' => array(
'key121' => 'value121',
'key122' => 'value122',
'key123' => 'value123',
'key124' => array('A','B','C','D'),
),
),
'key2' => array(
'key21' => array(
'key211' => 'value111',
'key212' => 'value112',
'key213' => 'value113',
'key214' => array('A','B','C','D'),
),
),
);
Script:
function remap_keys($input, $max_depth, $separator = '/', /* reserved */ $keychain = array(), /* reserved */ &$output = array())
{
foreach ($input as $key => $element)
{
$element_keychain = array_merge($keychain, (array)$key);
if (($max_depth > 1) && is_array($element))
remap_keys($element, $max_depth -1, $separator, $element_keychain, $output);
else
$output[implode($separator, $element_keychain)] = implode(',', (array)$element);
}
return $output;
}
$array = remap_keys($array, 3);
print_r($array);
Output:
Array
(
[key1/key11/key111] => value111
[key1/key11/key112] => value112
[key1/key11/key113] => value113
[key1/key11/key114] => A,B,C,D
[key1/key12/key121] => value121
[key1/key12/key122] => value122
[key1/key12/key123] => value123
[key1/key12/key124] => A,B,C,D
[key2/key21/key211] => value111
[key2/key21/key212] => value112
[key2/key21/key213] => value113
[key2/key21/key214] => A,B,C,D
)
http://ideone.com/pqH45h
$array = array('key1' =>
array('key11' =>
array('key111' => 'value111',
'key112' => 'value112',
'key113' => 'value113',
'key114' => array(A,B,C,D),
),
),
);
function implode_arr_keys($array, $output_arr = array(), $cur_key = FALSE) {
foreach($array as $key => $value) {
if(is_array($value)) {
return implode_arr_keys($value, $output_arr, ($cur_key == FALSE ? $key : $cur_key.'/'.$key));
} else {
if(!is_numeric($key))
$output_arr[$cur_key.'/'.$key] = $value;
else
$output_arr[$cur_key] = $array;
}
}
return $output_arr;
}
print_r($array);
print_r(implode_arr_keys($array));

Just cant get the for loop to produce needed array in Php

I need my for loop to return an array that looks like this
$nullArray =array(
0 => array("id" => 1, "label" => "test 1", "type" => "folder"),
array("id" => 2, "label" => "test 2", "type" => "folder"),
array("id" => 3, "label" => "test 3", "type" => "folder"),
etc...
etc...
etc...
);
what I have right now
$nullArray = array();
$numOfVer = mysql_num_rows($result);
$startArray= array();
//SETS FIRST NODE
for($i =0;$i < $numOfVer;$i++)
{
$label = mysql_result($result, $i);
$id = $i+1;
$startArray = array(array('id' => $id,'label' => $label, "type" => "folder"));
//$startArray[]['id'] = $id;
//$startArray[]['label'] = $label;
//$startArray[]['type'] = "folder";
//array_push($startArray,array(array('id' => $id,'label' => $label, "type" => "folder")));
//$nullArray[0]= array(array('id' => $id,'label' => $label, "type" => "folder"));
//array_push($nullArray[0],array('id' => $id,'label' => $label, "type" => "folder"));
}
$nullArray[0] = $startArray;
echo json_encode($nullArray[0]);
Everything that I have commented out is something that I have tried and it has failed. I'v been at it for too long for something so simple so I decided to get some help! Thank you in advance! :)
In for loop you are redclaring your $startArray thats why the previous value removed. Try this.
$nullArray = array();
$numOfVer = mysql_num_rows($result);
$startArray= array();
for($i =0;$i < $numOfVer;$i++)
{
$label = mysql_result($result, $i);
$id = $i+1;
$startArray[] = array('id' => $id,'label' => $label, "type" => "folder");
}

substr by using array as condition

I have a file contain text
ABBCDE1990-12-10JOBALPHABETabbcde1990-12-10jobalphabet
$field = array(
"fullname" => array("length"=5,"mandat"=>True),
"bithday" => array("length"=>10,"mandat"=>True)
"job" => array("length"=>3,"mandat"=>True),
"desc" => array("length"=>8,"mandat"=>false)
);
How can I get the array some thing like this:
$output = array(
//ABBCDE1990-12-10JOBALPHABET
0=>array(
"fullname" => "ABBCDE"
"bithday" => 1990-12-10
"job" => "JOB"
"desc"=> "ALPHABET"
)
//abbcde1990-12-10jobalphabet
1=>array(
"fullname" => "abbcde"
"bithday" => 1990-12-10
"job" => "job"
"desc"=> "alphabet"
)
);
I am tryin to buld a function
function toOutput($str,$filed){
$per_line = 27;//len of abbcde1990-12-10jobalphabet
$pos = 0;
while ($pos<strlen($str)){
$pos += 27;
//
}
}
$field = array(
"fullname" => array("length"=>6,"mandat"=>True),
"bithday" => array("length"=>10,"mandat"=>True),
"job" => array("length"=>3,"mandat"=>True),
"desc" => array("length"=>8,"mandat"=>false)
);
$string = 'ABBCDE1990-12-10JOBALPHABETabbcde1990-12-10jobalphabet';
$result = array();
$countString = strlen($string)/27;
$oldPos = 0;
for($i=0;$i<$countString;$i++) {
foreach($field as $k=>$v) {
$result[$i][$k] = substr($string,$oldPos,$v['length']);
$oldPos += $v['length'];
}
}
print_r($result);
You can see it up and running here: http://codepad.org/CEQNIPCg (version 0.3)
Based on that you can create a function so you can pass to it all $string that you have

Categories