Last active
September 17, 2018 17:36
-
-
Save vuthaihoc/4935e3f581352ef8a6590899bd0cb782 to your computer and use it in GitHub Desktop.
Tiny Problems
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- Problem 1: Cho mảng nhiều chiều | |
[ | |
a => 1, | |
b => 2, | |
c => [ | |
d => 4, | |
e => 5, | |
f => [ g => 6] | |
] | |
] | |
xây dựng hàm flat(...) làm nhiệm vụ làm phẳng mảng với key được nối từ các key gốc, giá trị là giá tị không phải mảng trong cùng. | |
[ | |
a => 1, | |
b => 2, | |
c.d => 4, | |
c.e => 5, | |
c.f.g => 6 | |
] | |
function flat($array, $prefix = '') { | |
if (!is_array($array)) { | |
return false; | |
} | |
$result = []; | |
foreach ($array as $key => $value) { | |
if (is_array($value)) { | |
$new_prefix = $prefix . "$key."; | |
$result = array_merge($result, flat($value, $new_prefix)); | |
} else { | |
$result[$prefix.$key] = $value; | |
} | |
} | |
return $result; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function flat($array, $prefix = '') { | |
if (!is_array($array)) { | |
return false; | |
} | |
$result = []; | |
foreach ($array as $key => $value) { | |
if (is_array($value)) { | |
$new_prefix = $prefix . "$key."; | |
$result = array_merge($result, flat($value, $new_prefix)); | |
} else { | |
$result[$prefix.$key] = $value; | |
} | |
} | |
return $result; | |
} | |
$array = [ | |
"a" => 1, | |
"b" => 2, | |
"c" => [ | |
"d" => 4, | |
"e" => 5, | |
"f" => [ | |
"g" => 6, | |
"h" => [ | |
"k" | |
] | |
] | |
] | |
]; | |
print_r(flat($array)); | |
////////// output | |
// Array | |
// ( | |
// [a] => 1 | |
// [b] => 2 | |
// [c.d] => 4 | |
// [c.e] => 5 | |
// [c.f.g] => 6 | |
// [c.f.h.0] => k | |
// ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment