I have a string like 1-350,9-390.99,...
, and I need to turn it into an associative array like this:
Array
(
[1] => 350
[9] => 390.99
...........
)
Is it possible to do this using only array functions, without a loop?
PHP 5.5+ two-line solution, using array_chunk
and array_column
:
$input = '1-350,9-390.99';
$chunks = array_chunk(preg_split('/[-,]/', $input), 2);
$result = array_combine(array_column($chunks, 0), array_column($chunks, 1));
print_r($result);
Yields:
Array
(
[1] => 350
[9] => 390.99
)
See it online at 3v4l.org.
Here's a way to do it without a for loop, using array_walk:
$array = explode(',', $string);
$new_array = array();
array_walk($array,'walk', $new_array);
function walk($val, $key, &$new_array){
$nums = explode('-',$val);
$new_array[$nums[0]] = $nums[1];
}
Example on Ideone.com.
Something like this should work:
$string = '1-350,9-390.99';
$a = explode(',', $string);
foreach ($a as $result) {
$b = explode('-', $result);
$array[$b[0]] = $b[1];
}
This uses array_walk with a closure.
<?php
$string = "1-350,9-390.99";
$partial = explode(',', $string);
$final = array();
array_walk($partial, function($val,$key) use(&$final){
list($key, $value) = explode('-', $val);
$final[$key] = $value;
});
print_r($final);
?>
Interactive fiddle.
$string = '1-350,9-390.99........';
$final_result = array();
foreach (explode(',', $string) as $piece) {
$result = array();
$result[] = explode('-', $piece);
$final_result[$result[0]] = $result[1];
}
print_r($final_result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With