I have the following array:
Array
(
[0] => 102 [30:27]
[1] => 110 [29:28]
[2] => 103 [30:27]
)
The output I need is as follows:
Array
(
[102] => 30:27
[110] => 29:28
[103] => 30:27
)
How can I do this?
If the data is consistent then is there any need for expensive regex? Here's the working version.
$array = array(
'102 [30:27]',
'110 [29:28]',
'103 [30:27]'
);
$new = array();
array_walk($array, function($element) use (&$new) {
$parts = explode(" ", $element);
$new[$parts[0]] = trim($parts[1], ' []');
});
var_dump($new);
You can loop through the array, use a regular expression to capture both the number and value, and then build a new array with the number as the index:
$result = array();
foreach ($array as $key => $value) {
if (preg_match('~(\d+)\s+\[(.*)]~', $value, $matches)) {
$index = isset($matches[1]) ? $matches[1] : $key;
$value = isset($matches[2]) ? $matches[2] : $key;
$result[$index] = $value;
}
}
print_r($result);
If the array values are always delimited by a single space, then a regular expression isn't necessary. You could use explode() to split the array value with space as a delimiter and then get the index and value to build the new array:
$result = array();
foreach ($array as $key => & $value) {
$parts = explode(' ', $value);
$index = $parts[0];
$result[$index] = substr($parts[1], 1, -1);
}
print_r($result);
Output:
Array
(
[102] => 30:27
[110] => 29:28
[103] => 30:27
)
When parsing a regularly formatted string which is not natively parse-able by PHP, sscanf() or preg_match() will often provide the most direct solution.
Parse the whole leading number with %d, then isolate the non-closing-brace characters after the opening brace character. The closing brace is ignored for this task because the goal is not to validate the strings, but to parse their valuable substrings. Demo
Functional-style iteration:
var_export(
array_reduce(
$array,
function ($result, $v) {
[$k, $result[$k]] = sscanf($v, '%d [%[^]]');
return $result;
},
[]
)
);
Language construct iteration:
$result = [];
foreach ($array as $v) {
[$k, $result[$k]] = sscanf($v, '%d [%[^]]');
}
var_export($result);
102 [30:27]value of[0]key or you write here for explanation? you can chnage array value to key by usingarray_flip()array function in php