如何在PHP中将CSV字符串转换为关联数组 [英] How to convert CSV String to Associative array in PHP
本文介绍了如何在PHP中将CSV字符串转换为关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
几乎重复了类似的问题.
Almost similar questions are repeated.
我正在针对不同的问题从数据库中更新和获取字符串.
I am updating and fetching string from database for different issues.
让我们说从数据库中获取值后,我的变量$str
之一看起来像下面的变量之一
lets say after fetching value from database one of my variable $str
looks like one of the below
$str = "1:1,2:1,3:2,5:6";
或
$str = "1|1,2|1,3|2,5|6";
或
$str = "1=1,2=1,3=2,5=6";
如何在PHP中将任何人或几乎不同的字符串转换为关联数组
how can I convert anyone or almost different string to an associative array in PHP
先谢谢了.我尝试寻找答案,但没有找到任何类似的答案.
thanks in advance. I tried for an answer but didnt find anything similar.
代码我试图使其成为一个关联数组
code i tried to make it an associative array
$firstArr = explode(',', $str);
foreach (firstArr as $value) {
$secondArr = explode(':', $value);
}
推荐答案
尝试一下:
$final_array = Array();
$str = "1|1,2|1,3|2,5|6";
$arr1 = explode(",", $str);
// this gives $arr1 as
// array(4) { [0]=> string(3) "1|1" [1]=> string(3) "2|1" [2]=> string(3) "3|2" [3]=> string(3) "5|6" }
// iterate through $arr1 and further split it on | using explode function
foreach ($arr1 as $k=>$v){
$arr2 = explode("|", $v);
// $arr2 would be like
// array(2) { [0]=> string(1) "1" [1]=> string(1) "1" } etc.
$final_array[$arr2[0]] = $arr2[1];
}
print_r($final_array);
// gives Array ( [1] => 1 [2] => 1 [3] => 2 [5] => 6 )
但是正如Sylvain所述,您可能还需要研究数据库规范化部分.
But as Sylvain mentioned, you might also want to look into your database normalization part.
这篇关于如何在PHP中将CSV字符串转换为关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文