我正在尝试在关联数组中同时定位键和值,以删除双引号字符串。我通过JSON.stringify将一个字符串传递给php控制器,如下所示:
"searchFilterType":"inside","searchFilterField":"okay","searchFilterGeoDistance":"27","searchFilterZip":"2","keyword":"test"
我将其分配给变量$string;
我使用以下内容将其分解为一个数组:
$sExplode = explode(',', $string);
$searchFilters = [];
哪个给我
[0] => "searchFilterType":"inside"
[1] => "searchFilterField":"okay"
[2] => "searchFilterGeoDistance":"25"
[3] => "searchFilterZip":""
[4] => "keyword":"test"
然后我将其分解为关联数组:
foreach ($sExplode as $v) {
$v = explode(":",$v);
$searchFilters[$v[0]] = $v[1];
}
哪个给我:
["searchFilterType"] => "inside"
["searchFilterField"] => "okay"
["searchFilterGeoDistance"] => "27"
["searchFilterZip"] => "2"
["keyword"] => "test"
然后我使用以下方法从值中删除字符串:
$searchFilters = preg_replace("/[^a-zA-Z 0-9]+/", "", $searchFilters);
给我:
["searchFilterType"] => inside
["searchFilterField"] => okay
["searchFilterGeoDistance"] => 27
["searchFilterZip"] => 2
["keyword"] => test
但是我仍然需要删除数组键中的字符串。我的主要目标是达到以下目标:
[searchFilterType] => inside
[searchFilterField] => okay
[searchFilterGeoDistance] => 27
[searchFilterZip] => 2
[keyword] => test
有比这更简单的解决方案了吗?
答案 0 :(得分:1)
如果$string
是JSON,最简单的方法是使用json_decode
。
$result = json_decode($string, true);
如果$string
是一个JSON片段(如您在问题中所示),那么最简单的操作仍然可能是json_decode
。您只需添加方括号即可完成解码。
$data = json_decode('{'.$string.'}', true);
答案 1 :(得分:0)
如果您不想沿着JSON路线走,这将以相同的方式执行explode()
,然后遍历结果数组并像对待定字符串一样处理它(使用{{1 }}),以str_getcsv()
作为分隔符,并允许其删除引号。
最后使用:
将键和值组合到一个关联数组中...
array_column()
给..
$string = '"searchFilterType":"inside","searchFilterField":"okay","searchFilterGeoDistance":"27","searchFilterZip":"2","keyword":"test"';
$sExplode = explode(',', $string);
$map = array_map(function ( $value ) { return str_getcsv($value, ":", '"'); }, $sExplode);
$out = array_column($map, 1, 0);
print_r($out);