Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions data.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"one":
{
"two": 3,
"four": [ 5,6,7]
},
"eight":
{
"nine":
{
"ten":11
}
}
}
79 changes: 79 additions & 0 deletions ontraport.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

class Ontraport {

public $result = [];

public function MultiToOneDimentionalArray($list, $str)
{
if(is_array($list) && sizeof($list) > 0) {
foreach ($list as $key => $value) {
if(is_array($value) && sizeof($value) > 0) {
$str .= $key . '/';
$this->MultiToOneDimentionalArray($value, $str);
} else {
if($str != '') {
$temp = $str;
$str .= $key . ':'. $value;
array_push($this->result, $str);
$str = $temp;
} else {
$str .= $key . ':'. $value;
array_push($this->result, $str);
$str = '';
}
}
}
}
return json_encode($this->result, JSON_UNESCAPED_SLASHES);
}

public function OneToMultidimentionalArray($data) {

$result = [];
foreach ($data as $key => $value) {
$explode_data = explode('/', $key);
$output = &$result;
while (count($explode_data) > 1) {
$output = &$output[array_shift($explode_data)];
if (!is_array($output)) $output = [];
}
$output[array_shift($explode_data)] = $value;
}
return $result;
}
}

$ontra = new Ontraport();

$result1 = $ontra->MultiToOneDimentionalArray(json_decode(file_get_contents("data.json"), JSON_OBJECT_AS_ARRAY), '');
/*
Output of result1 is
{
'one/two':3,
'one/four/0':5,
'one/four/1':6,
'one/four/2':7,
'eight/nine/ten':11
}
*/
$result2 = $ontra->OneToMultidimentionalArray(json_decode(file_get_contents("reverse_data.json"), JSON_OBJECT_AS_ARRAY));
/*
Output of result1 is
{
{
'one':
{
'two': 3,
'four': [ 5,6,7]
},
'eight':
{
'nine':
{
'ten':11
}
}
}
}
*/
7 changes: 7 additions & 0 deletions reverse_data.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"one/two":3,
"one/four/0":5,
"one/four/1":6,
"one/four/2":7,
"eight/nine/ten":11
}