Created
October 19, 2018 09:04
-
-
Save dyazincahya/802772e727fd1220f50e06717d99273d to your computer and use it in GitHub Desktop.
Function php string array to real array
This file contains 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 | |
function strarr_to_array($a, $t = ''){ | |
$arr = []; | |
$a = ltrim($a, '['); | |
$a = ltrim($a, 'array('); | |
$a = rtrim($a, ']'); | |
$a = rtrim($a, ')'); | |
$tmpArr = explode(",", $a); | |
foreach ($tmpArr as $v) { | |
if($t == 'keys'){ | |
$tmp = explode("=>", $v); | |
$k = $tmp[0]; $nv = $tmp[1]; | |
$k = trim(trim($k), "'"); | |
$k = trim(trim($k), '"'); | |
$nv = trim(trim($nv), "'"); | |
$nv = trim(trim($nv), '"'); | |
$arr[$k] = $nv; | |
} else { | |
$v = trim(trim($v), "'"); | |
$v = trim(trim($v), '"'); | |
$arr[] = $v; | |
} | |
} | |
return $arr; | |
} | |
// usage | |
$test = '["me","and","you","just","a","friend","Ohhhhhhhhh!","sad"]'; | |
echo "<pre>"; | |
print_r(strarr_to_array($test)); | |
// result | |
Array | |
( | |
[0] => me | |
[1] => and | |
[2] => you | |
[3] => just | |
[4] => a | |
[5] => friend | |
[6] => Ohhhhhhhhh! | |
[7] => sad | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment