I have string :
$string = "'id_konversi_aktivitas' => 'f4d943e7', 'nim' => '180218038'"
And I will convert to array like this :
$data = array($string);
But the result is like this :
array(1) { [0]=> string(87) "'id_konversi_aktivitas' => 'f4d943e7', 'nim' => '180218038'" }
I want result like this :
array(2) { ["id_konversi_aktivitas"] => "f4d943e7", ["nim"] => "180218038" }
CodePudding user response:
there is no core PHP function to achieve what you are looking for. You can try in the following way.
$string = "'id_konversi_aktivitas' => 'f4d943e7', 'nim' => '180218038'";
$arrayStr = explode(',', $string);
$myArr = [];
foreach ($arrayStr as $arr) {
$eachArr = explode('=>', $arr);
$myArr[trim($eachArr[0])] = $eachArr[1];
}
print_r($myArr);
CodePudding user response:
I made a function specifically for this problem, I hope it helps you out.
function stringToArray($string) {
$output = [];
$array = explode(",", $string);
foreach($array as $elem) {
$item = explode("=>", $elem);
$newItem = [
trim(str_replace("'", "", $item[0])) => $item[1]
];
array_push($output, $newItem);
}
return $output;
}
Here's how I used it
<?php
$string = "'id_konversi_aktivitas' => 'f4d943e7', 'nim' => '180218038'";
function stringToArray($string) {
$output = [];
$array = explode(",", $string);
foreach($array as $elem) {
$item = explode("=>", $elem);
$newItem = [
trim(str_replace("'", "", $item[0])) => $item[1]
];
array_push($output, $newItem);
}
return $output;
}
$data = stringToArray($string);
print_r($data[0]["id_konversi_aktivitas"]);
// >> 'f4d943e7'