Yellow and Red Yellow and Red - 4 months ago 14
SQL Question

How to convert CSV String to Associative array in PHP

Almost similar questions are repeated.

I am updating and fetching string from database for different issues.

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";


or

$str = "1|1,2|1,3|2,5|6";


or

$str = "1=1,2=1,3=2,5=6";


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);
}

Answer

Try this:

$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 ) 

But as Sylvain mentioned, you might also want to look into your database normalization part.

Comments