Skip to content

Instantly share code, notes, and snippets.

@samurai00
Created May 14, 2014 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samurai00/3ad90cb7a7cb09fc6299 to your computer and use it in GitHub Desktop.
Save samurai00/3ad90cb7a7cb09fc6299 to your computer and use it in GitHub Desktop.
simple array to simple text; simple text to simple array
<?php
$cats = array(
array(
'id' => 1,
'name' => 'level1_1',
'children' => array(
array(
'id' => 1,
'name' => 'level2_1',
'children' => array(
array(
'id' => 1,
'name' => 'level3_1',
'children' => null,
),
array(
'id' => 1,
'name' => 'level3_2',
'children' => array(
array(
'id' => 1,
'name' => 'level4_1',
'children' => null,
),
array(
'id' => 1,
'name' => 'level4_2',
'children' => null,
),
),
),
),
),
array(
'id' => 1,
'name' => 'level2_2',
'children' => array(
array(
'id' => 1,
'name' => 'level3_1',
'children' => null,
),
array(
'id' => 1,
'name' => 'level3_2',
'children' => null,
),
),
),
),
),
array(
'id' => 2,
'name' => 'level1_2',
'children' => array(
array(
'id' => 1,
'name' => 'level2_1',
'children' => null,
),
// ...
),
),
array(
'id' => 3,
'name' => 'level1_3',
'children' => array(
array(
'id' => 1,
'name' => 'level2_1',
'children' => null,
),
// ...
),
),
array(
'id' => 4,
'name' => 'level1_4',
'children' => array(
array(
'id' => 1,
'name' => 'level2_1',
'children' => null,
),
// ...
),
),
);
function toTxt($children, $level) {
if (is_array($children)) {
$str = '';
foreach ($children as $row) {
if (strlen($str) != 0) {
$str .= "\n";
}
$str .= str_repeat(' ', $level) . $row['id'] . '=>' . $row['name'];
$children_str = toTxt($row['children'], $level + 1);
if (strlen($children_str) != 0) {
$str .= "\n" . toTxt($row['children'], $level + 1);
}
}
return $str;
} else {
return '';
}
}
$str = toTxt($cats, 0);
file_put_contents("./output.txt", $str);
function toArray($str) {
preg_match_all("/(^|\n)(((\s{4})*)([^\s]+))/", $str, $matches);
$arr = array();
foreach ($matches[3] as $index => $row) {
$strs = explode("=>", $matches[5][$index]);
$current_level = strlen($row)/4;
if ($current_level == 0) {
$tmp = &$arr;
} else {
$tmp = &$arr;
for ($i=0; $i < $current_level; $i++) {
$tmp = &$tmp[count($tmp)-1];
if ($tmp['children'] == null) {
$tmp['children'] = array();
}
$tmp = &$tmp['children'];
}
}
$tmp[count($tmp)] = array(
'id' => $strs[0],
'name' => $strs[1],
'children' => null
);
unset($tmp);
}
return $arr;
}
$data = file_get_contents("./output.txt");
$array = toArray($data);
var_export($array);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment