I have a string in the following form:
$my_original_string = "A value1,A value2,E value3,A value4";
The first letter is a sort of label, the value is associated with a label.
I must manipulate and convert my string to the following:
$my_converted_string = "A: value1 value2 value4, E: value3";
With a simple loop, I created an array $temp:
$my_original_string = "A value1,A value2,E value3,A value4";
$original_string_to_array = explode(",", $my_original_string);
$o_len = count($original_string_to_array);
$temp = [];
for($i=0; $i<$o_len; $i++){
$temp[explode(" ",$original_string_to_array[$i])[0]][] = explode(" ",$original_string_to_array[$i])[1];
}
print_r($temp);
/*
Result:
Array
(
[A] => Array
(
[0] => value1
[1] => value2
[2] => value4
)
[E] => Array
(
[0] => value3
)
)
*/
Starting from here, I could eventually loop again to build my new string. Or maybe I could do it even in one loop.
But, is there anything better I could do? I checked the capabilities of array_map, array_filter and array_walk but I could not find a way to apply them in this particular case.
Thanks in advance.
implode()to turn an array into a comma-separated string.array_map()because it only gets the values, not the keys. So use aforeach()loop to push each key and the imploded values into another array, then implode that to get the final result.