From a08d9e7563318eab690114175b117177f473b9ee Mon Sep 17 00:00:00 2001 From: meghana Vemuri Date: Mon, 5 Sep 2022 19:30:28 -0400 Subject: [PATCH 1/2] Ontraport Interview Code Changes --- data.json | 14 ++++++++ ontraport.php | 82 +++++++++++++++++++++++++++++++++++++++++++++++ reverse_data.json | 7 ++++ 3 files changed, 103 insertions(+) create mode 100644 data.json create mode 100644 ontraport.php create mode 100644 reverse_data.json diff --git a/data.json b/data.json new file mode 100644 index 0000000..df72457 --- /dev/null +++ b/data.json @@ -0,0 +1,14 @@ +{ + "one": + { + "two": 3, + "four": [ 5,6,7] + }, + "eight": + { + "nine": + { + "ten":11 + } + } +} \ No newline at end of file diff --git a/ontraport.php b/ontraport.php new file mode 100644 index 0000000..4dc08bb --- /dev/null +++ b/ontraport.php @@ -0,0 +1,82 @@ + 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 + } + } +} +} +*/ \ No newline at end of file diff --git a/reverse_data.json b/reverse_data.json new file mode 100644 index 0000000..c06a9c1 --- /dev/null +++ b/reverse_data.json @@ -0,0 +1,7 @@ +{ + "one/two":3, + "one/four/0":5, + "one/four/1":6, + "one/four/2":7, + "eight/nine/ten":11 +} \ No newline at end of file From bfc72443e83579fff7a74c1aeb3c308915492f3f Mon Sep 17 00:00:00 2001 From: meghana Vemuri Date: Mon, 5 Sep 2022 22:43:32 -0400 Subject: [PATCH 2/2] changes --- ontraport.php | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/ontraport.php b/ontraport.php index 4dc08bb..c60bde5 100644 --- a/ontraport.php +++ b/ontraport.php @@ -1,8 +1,5 @@