简体   繁体   English

如何在PHP中将逗号分隔的键值字符串转换为关联数组

[英]How to convert comma separated key value string to associative array in PHP

I tried searching for a quick fix to converting a comma separated key=>value string to an associative array but couldn't find any. 我尝试搜索一种快速解决方案,以将逗号分隔的key => value字符串转换为关联数组,但找不到任何数组。 So i had to make a quick fix myself. 所以我不得不自己快速修复。

ANTECEDENT 事前

I generated an array of some form elements using Jquery, to be sent via ajax. 我使用Jquery生成了一些表单元素的数组,并通过ajax发送。 So I have something like: 所以我有这样的事情:

var myarray = [];
var string1 = 'key1=>'+form['value1'].value; //and we have string2 and more
myarray.push(string1);

Then i sent "myarray" as data to the form handling script. 然后,我将“ myarray”作为数据发送到表单处理脚本。

PROBLEM 问题

Now i have an array to deal with in my php script. 现在我要在我的PHP脚本中处理数组。 I have the following: 我有以下内容:

function($var,$data){
$string = $data('myarray'); //array created earlier with jquery
}

Which is the same as: 与以下内容相同:

...
$string = array(0=>'key1=>value1',1=>'key2=>value2');
...

Meanwhle, what i need is: 意思是,我需要的是:

...
$string = array('key1'=>'value1','key2'=>'value2');
...

SOLUTION

...
$string = $data('myarray');
$string1 = array();
foreach($string as $value){
    $split = explode('=>',$value);
    $string1[$split[0]]=$split[1];
}
...

Now i can access the value of each key as: 现在,我可以按以下方式访问每个键的值:

echo $string1['key1']; //gives value1

This solution can also be used in a situation where you have: 此解决方案还可以用于以下情况:

$string = 'key1=>value1,key2=>value2...';
$string = explode(',',$string); // same as $string = array('key1'=>'value1',...)
$string1 = array();
foreach($string as $value){
    $split = explode('=>',$value);
    $string1[$split[0]]=$split[1];
}

The solution is rather simpler than i expected but if you know a better way to make this kind of conversion, feel free to suggest. 解决方案比我预期的要简单得多,但是如果您知道进行这种转换的更好方法,请随时提出建议。

You can add as key value pair in javascript. 您可以在javascript中添加作为键值对。 Then you don't need to do any operations, can access directly in PHP. 然后,您无需执行任何操作,就可以直接在PHP中进行访问。

var myarray = {};
myarray['key1'] = form['value1'].value;

In PHP : 在PHP中:

$arr = $data('myarray');
echo $arr['key1']

Use explode() to split up the string. 使用explode()分割字符串。

$string = 'key1=>value1,key2=>value2,key3=>value3';
$pairs = explode(',', $string);
$data = array();
foreach ($pairs as $pair) {
    list($key, $value) = explode('=>', $pair);
    $data[$key] = $value;
}
var_dump($data);

DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM